1. 程式人生 > >100. Same Tree(五星)

100. Same Tree(五星)

same leetcode java iss keyword emp bsp nbsp return

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