码迷,mamicode.com
首页 > 其他好文 > 详细

100. Same Tree(五星)

时间:2018-02-28 01:10:54      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:.com   自己的   sametree   nbsp   empty   rally   树结构   链接   答案   

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(五星)

标签:.com   自己的   sametree   nbsp   empty   rally   树结构   链接   答案   

原文地址:https://www.cnblogs.com/mafang/p/8480409.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!