100. Same Tree(二叉树、递归)

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.

给出两个二叉树,写一个算法来检查它们是否相同。若两棵树结构完全相同,且每个节点有相同值,则为两棵树相同。

Example 1:

Input:     1         1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

Output: true

 

Example 2:

Input:     1         1
          /           \
         2             2

        [1,2],     [1,null,2]

Output: false

 

Example 3:

Input:     1         1
          / \       / \
         2   1     1   2

        [1,2,1],   [1,1,2]

Output: false

大神答案micheal.zhou

递归方式,简单明了~
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 isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    return false;
}
 

 我自己的答案(非递归),这个题其实主要考察二叉树的遍历,下面链接里非常详细地总结了二叉树前、中、后序遍历的递归和非递归方法,可读性比较高。

http://blog.csdn.net/apandi_/article/details/52916523

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.Stack;

class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
Stack<TreeNode> st_p = new Stack<TreeNode>();
Stack<TreeNode> st_q = new Stack<TreeNode>();

while (p != null || !st_p.empty()) {
while (p != null) {
if (q == null)
return false;

if (p.val != q.val)
return false;

st_p.push(p);
st_q.push(q);
p = p.left;
q = q.left;
}

if (!st_p.empty()) {
if(st_q.empty()||q!=null)
return false;
p=st_p.pop();
q=st_q.pop();
p=p.right;
q=q.right;
}
}

if (q!=null||!st_q.empty())
return false;

return true;
}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值