剑指offer-树的子结构

来源:互联网 发布:哪个网站有卖淘宝小号 编辑:程序博客网 时间:2024/05/16 12:56

分析

  1. 大体思路如下:
    • 判断当前节点与查询节点的val是否相等,若相等,则去检查两者的左右子树;
    • 反之return false;
  2. 在程序递归过程中,记得注意递归的出口以及空指针的处理;主程序中在root1&root2非空的条件下才能去判断;
  3. 判断judge函数中,一些边界出口为
if(root2 == null) return true;if(root1 == null) return false;

代码

public class Solution {    public boolean HasSubtree(TreeNode root1,TreeNode root2) {        boolean res = false;        if (root1 != null && root2 != null){            res = judge(root1, root2);            /**                记得放到里面,否则空指针异常            **/            if(!res){                res = judge(root1.left, root2);            }            if(!res){                res = judge(root1.right, root2);            }        }        return res;    }    public boolean judge(TreeNode root1, TreeNode root2){        // 注意对root1,root2为空的判断!!!        if(root2 == null){            return true;        }         if(root1 == null){           return false;        }else if(root1.val == root2.val){           return judge(root1.left, root2.left) && judge(root1.right, root2.right);        }else{           return false;        }    }}
0 0
原创粉丝点击