Same Tree:
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
题目要求:
给定两个二叉树,写一个函数来检查它们是否相投。
如果两个二叉树的结构相同并且结点有相同的值,我们就认为两个二叉树相同。
解题思路:
这类问题可以使用递归的方法来解决很简单,先检查结点是否同时为空,是则相同,否则不同,然后分别以左结点和右结点作为结点递归的调用自己,都相同则相同,否则不同。
Java :
非递归:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
// Start typing your Java solution below
// DO NOT write main() function
LinkedList<TreeNode> t1 = new LinkedList<TreeNode>();
LinkedList<TreeNode> t2 = new LinkedList<TreeNode>();
t1.add(p);
t2.add(q);
while(!t1.isEmpty() && !t2.isEmpty()){
TreeNode c1 = t1.poll();
TreeNode c2 = t2.poll();
if(c1==null&&c2==null) continue;
if(c1==null||c2==null) return false;
if(c1.val!=c2.val) return false;
t1.add(c1.left);
t1.add(c1.right);
t2.add(c2.left);
t2.add(c2.right);
}
return true;
}
}
递归是引用的:
http://blog.youkuaiyun.com/linhuanmars/article/details/22839819
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==null && q==null)
return true;
if(p==null || q==null)
return false;
if(p.val!=q.val)
return false;
return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
}