100. Same Tree

题目:

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.

链接: http://leetcode.com/problems/same-tree/

题解:判断二叉树是否相同。 假如根节点都为空,则返回true; 根节点仅有一个为空,返回false; 根节点值相同,recursively比较两个子节点; 根节点值不同返回false。

Time Complexity - O(n), Space Complexity - O(n)

public class Solution {
    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);
        else
            return false;
    }
}

二刷:

先判断p和q为null的情况,接下来判断p和q的值是否相当,最后递归判断p和q左右子树是否相等。

也可以用stack或者queue来做两棵树的traversal。看了一下discuss,有用两个stack的,也有用一个stack的,以后再继续研究。

Java:

Time Complexity - O(n), Space Complexity - O(n)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null || q == null) {
            return p == null && q == null;
        }
        if (p.val != q.val) {
            return false;
        } else {
            return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
        }
    }
}

三刷:

要好好学一下coding style的line wrapping

Java:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null || q == null) {
            return p == q;
        }
        return (p.val == q.val) 
               ? isSameTree(p.left, q.left) && isSameTree(p.right, q.right) 
               : false;
    }
}

Reference:

http://yohanan.org/steve/projects/java-code-conventions/#SECTION00052000000000000000

http://www.oracle.com/technetwork/articles/javase/codeconvtoc-136057.html

http://www.oracle.com/technetwork/java/codeconventions-150003.pdf

原文地址:https://www.cnblogs.com/yrbbest/p/4437176.html