您的位置:首页 > 其它

关于Leetcode中Same Tree一题的理解

2016-08-21 20:41 351 查看
题目如下:

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.

下面附有一个TreeNode的数据结构:

/**
* 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 true;
if(p == null || q == null)return false;
return (p.val==q.val) && isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
}
}


    如果非要说有什么启示的话,就是在需要同时根据一个节点的左儿子节点和右儿子节点及自身属性获得一个bool值的时候,用“与”操作将这些结果联系在一起。

    但是这不是我要说的重点,重点出现在我非常naive的时候写出的一段代码,如下所示:

public class Main {

public static void main(String[] args) {
Solution sol = new Solution();
TreeNode node1 = new TreeNode(0);
node1.left = new TreeNode(-5);
TreeNode node2 = new TreeNode(0);
node2.left = new TreeNode(-8);

if (sol.isSameTree(node1, node2)) {
System.out.print("yes");
}else{
System.out.print("No");
}

}

public static class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q == null){
return true;
}else if(p !=null && q!=null){
if (p.val == q.val){
if ((p.left!=null && q.left==null) || (p.left==null && q.left!=null) || (p.right==null && q.right!=null) || (p.right!=null && q.right==null)){
return false;
}else if(p.left!=null){
isSameTree(p.left,q.left);
}else if(p.right!=null){
isSameTree(p.right,q.right);
}
}else{
System.out.println("777");
return false;
}
}else{
return false;
}
System.out.println("888");
return true;
}
}

public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}

}
运行结果如下图所示:



    你会发现这个结果是有些诡异的,程序输出777就代表已经返回了false值,那为什么还会继续执行输出888这条消息呢?程序不是已经返回了吗?

    产生这种现象的原因在与对return的理解存在偏差。return的含义就是“结束当前这个函数”,那到底是跳出这一层递归还是跳出整个递归是由我程序的写法决定的。程序里这种写法只是跳出该层的递归并不是跳出整个递归,在777输出后,执行return false操作只是会使下面这句代码:

isSameTree(p.left,q.left);

    变成false值,但是在上层递归中,这里并没有直接进行return返回,所以程序还需要向后继续进行,通过一系列判断之后,程序输出了888,然后返回了true值,所以最后得到的结果就是true而不是我YY的false。

    所以,在遇到二叉树的一些判断和递归时,尽量不要步步深入,否则会陷入if判断语句的汪洋大海。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode