leedcode做题总结,题目Symmetric Tree 2012/09/23
2014-07-12 23:32
302 查看
判断二叉树是否对称,用递归和非递归实现:
递归可以从节点朝两个方向同时访问比对
非递归思路也一样,从节点像两个方向同时访问比对,因为对用栈非递归历遍树的代码不是很熟悉,中间改了几次错误,代码比较乱。
递归可以从节点朝两个方向同时访问比对
public static boolean isS(TreeNode r1,TreeNode r2){ if(r1==null&&r2==null) return true; if(r1!=null&&r2!=null){ return isS(r1.left,r2.right)&&isS(r1.right,r2.left)&&r1.val==r2.val; } else{ return false; } } public static boolean isSymmetric(TreeNode root) { if(root==null) return true; return isS(root.left,root.right); }
非递归思路也一样,从节点像两个方向同时访问比对,因为对用栈非递归历遍树的代码不是很熟悉,中间改了几次错误,代码比较乱。
public boolean isSymmetric(TreeNode root) { if(root==null) return true; Stack<TreeNode> s1 = new Stack<TreeNode>(); Stack<TreeNode> s2 = new Stack<TreeNode>(); //s1.push(root); //s2.push(root); TreeNode root2=root; while (!(root==null&&root2==null)){ s1.push(root); if(root2==null)return false; if(root2.val!=root.val)return false; s2.push(root2); root = root.left; root2 = root2.right; if(root==null&&!s1.isEmpty()){ while(!s1.isEmpty()&&root==null&&!s2.isEmpty()&&root2==null){ root=s1.pop().right; root2=s2.pop().left; } if(root2!=null&&root==null)return false; if(root!=null&&root2==null)return false; if(!s1.isEmpty()&&s2.isEmpty())return false; if(!s2.isEmpty()&&s1.isEmpty())return false; } } return true; }
相关文章推荐
- leedcode做题总结,题目Flatten Binary Tree to Linked List 2012/10/14
- leedcode做题总结,题目Populating Next Right Pointers in Each NodeI/II---------- 2012/10/28
- leedcode做题总结, 题目Median 80
- leedcode做题总结,题目Single NumberI/II 2013/10/01-02
- leedcode做题总结,题目Binary Tree Level Order TraversalI/II 2012/09/28
- leedcode做题总结,题目Valid Palindrome 2013/01/12
- leedcode做题总结, 题目Maximum Subarray II & Maximum Subarray Difference
- leedcode做题总结, 题目Surrounded Regions130
- leedcode做题总结,题目Minimum Depth of Binary Tree 2012/10/09
- leedcode做题总结,题目Binary Tree Postorder Traversal-------- 2013/11/07
- leedcode做题总结,题目Reverse Integer----- 2011/12/25
- leedcode做题总结,题目Median of Two Sorted Arrays----- 2011/03/27
- leedcode做题总结,题目Reverse Words in a String14/03/05
- leedcode做题总结,题目Gas Station-------- 2013/09/28
- leetcode做题总结,题目Remove Duplicates from Sorted ListI/II 2012/04/22
- leedcode做题总结,题目Path SumI/II-------- 2012/10/13-14
- leedcode做题总结,题目Convert Sorted Array to Binary Search Tree 2013/02/18
- leetcode做题总结,题目Integer to Roman 2012/01/15
- leedcode做题总结,题目Reorder List 13/11/12
- leedcode做题总结,题目Pascal's Triangle I/II-------2012/10/28