题目描述:
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 a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==null&&q==null) return true;
if((p==null&&q!=null)||(q==null&&p!=null)||(p.val!=q.val)) return false;
Stack sk1=new Stack();
Stack sk2=new Stack();
sk1.push(p);
sk2.push(q);
while(p.left!=null&&q.left!=null){
TreeNode temp1=(TreeNode)sk1.peek();
TreeNode temp2=(TreeNode)sk2.peek();
p=temp1.left;
q=temp2.left;
sk1.push(p);
sk2.push(q);
if(p.val!=q.val) return false;
}
if(p.left!=null&&q.left==null||p.left==null&&q.left!=null) return false;
while(!sk1.isEmpty()&&!sk2.isEmpty()){
TreeNode temp1=(TreeNode)sk1.pop();
TreeNode temp2=(TreeNode)sk2.pop();
if(temp1.right!=null&&temp2.right==null||temp1.right==null&&temp2.right!=null) return false;
else if(temp1.right!=null&&temp2.right!=null){
p=temp1.right;
q=temp2.right;
sk1.push(p);
sk2.push(q);
if(p.val!=q.val) return false;
while(p.left!=null&&q.left!=null){
temp1=(TreeNode)sk1.peek();
temp2=(TreeNode)sk2.peek();
p=temp1.left;
q=temp2.left;
sk1.push(p);
sk2.push(q);
if(p.val!=q.val) return false;
}
if(p.left!=null&&q.left==null||p.left==null&&q.left!=null) return false;
}
}
return true;
}
}
原题题目:
https://leetcode.com/problems/same-tree/