FTPrep, 100 Same Tree

来源:互联网 发布:淘宝查号网址 编辑:程序博客网 时间:2024/05/31 13:14

一道简单题,但是是一个prototype 模版解题的开始,适用于任何用recursion 解决Binary Tree的问题。

1,base case,当root==null时,

2,root.left, root.right都为null时,即叶子节点

3,root.left or root right 有一个为null

这样写就非常保险,涵盖了root的四种情况,虽然在有些题中,这四种情况可以合并写一起,但是!强烈推荐老老实实清楚楚写出来,而不是因为要写出 syntactic sugar 而忽略的严谨。应该首先保证正确,然后再去美化代码。

前后两次写得代码,像个1-2周。

代码1:

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */class Solution {    public boolean isSameTree(TreeNode p, TreeNode q) {        if(p==null && q==null) return true;        if(p!=null && q!=null)  // since you have to compare the value, need to make sure it is not null            return (p.val==q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right));        return false; // 这里要加上这一句,要不编译器会缺少return value // 时候想想不是左边写的那个原因,而是要考虑到当p q有一个是null的时候,需要return false;    }}

代码2:

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */class Solution {    public boolean isSameTree(TreeNode p, TreeNode q) {        if(p==null && q==null) return true;        if((p!=null && q==null) || (p==null && q!=null)) return false; // I forget to check this, then get NullPointerError.        if(p.left==null&& p.right==null && q.left==null && q.right==null) return (p.val==q.val);        return (p.val==q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right));            }}