您的位置:首页 > 其它

leetcode100~Same Tree

2017-02-18 16:33 330 查看
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.

该题比较简单,不作解释,不懂的话,欢迎提问~

public class IsSameTree {
//递归实现
public boolean isSameTree(TreeNode p,TreeNode q) {
if(p==null && q==null) return true;
if(p==null || q==null) return false;
return (p.val==q.val) && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
//非递归
public boolean isSameTree2(TreeNode p,TreeNode q) {
Stack<TreeNode> stack = new Stack<>();
stack.push(p);
stack.push(q);
while(!stack.isEmpty()) {
q=stack.pop();
p=stack.pop();
if(p==null && q==null) continue;
if(p==null || q==null) return false;
if(p.val!=q.val) return false;

stack.push(p.left);
stack.push(q.left);

stack.push(p.right);
stack.push(q.right);
}
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: