该题目用来解决两棵二叉树是不是同一颗树!解决的方式是经过树的遍从来判断两棵树的节点是不是相等。 java
考虑到效率问题,该题目使用前序遍历比较好。比较不相等能够当即返回。 code
1. 采用非递归方式遍历树。 递归
public boolean isSameTree(TreeNode p, TreeNode q) { Stack<TreeNode> first = new Stack<TreeNode>(); Stack<TreeNode> second = new Stack<TreeNode>(); TreeNode fP = p; TreeNode sQ = q; while((fP!=null || !first.isEmpty()) && (sQ!=null || !second.isEmpty())){ if(fP==null || sQ == null){ return fP == sQ; } while(fP!=null && sQ!=null){ if(fP.val != sQ.val){ return false; } first.push(fP); second.push(sQ); fP = fP.left; sQ = sQ.left; } if(!first.isEmpty() && !second.isEmpty()){ fP = first.pop(); sQ = second.pop(); fP = fP.right; sQ = sQ.right; } } if(!first.isEmpty() || !second.isEmpty()){ return false; } return true; }
public boolean isSameTree(TreeNode p, TreeNode q) { if(p == null || q == null){ return p == q; } return (p.val == q.val) && isSameTree(p.left, q.left) && isSameTree(p.right, q.right); }