100. Same Tree

本文介绍了一种判断两棵二叉树是否相同的算法,并提供了详细的Java实现代码。该算法通过递归方式比较两棵树的结构和节点值,时间复杂度为O(n),空间复杂度也为O(n)。

题目:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值