题目描述:
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
思路一:
递归
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null)
return true;
else if (p == null || q == null)
return false;
if (p.val == q.val)
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
else return false;
}
}
思路二:Queue/Stackclass Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null)
return true;
else if (p == null || q == null)
return false;
Queue<TreeNode> q1 = new LinkedList<>();
Queue<TreeNode> q2 = new LinkedList<>();
q1.add(p);
q2.add(q);
while (!q1.isEmpty() && !q2.isEmpty())
{
TreeNode node1 = q1.poll();
TreeNode node2 = q2.poll();
if (node1.val != node2.val)
return false;
if (node1.left != null)
q1.add(node1.left);
if (node2.left != null)
q2.add(node2.left);
if (q1.size() != q2.size())
return false;
if (node1.right != null)
q1.add(node1.right);
if (node2.right != null)
q2.add(node2.right);
if (q1.size() != q2.size())
return false;
}
return true;
}
}