100. Same Tree(五星)

Posted 同销万古愁

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
}
}

以上是关于100. Same Tree(五星)的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode(100):Same Tree

100. Same Tree

100. Same Tree(LeetCode)

100. Same Tree(Tree)

LeetCode100. Same Tree-相同树

[LeetCode] 100. Same Tree ☆(两个二叉树是否相同)