LeetCode 572

https://leetcode-cn.com/problems/subtree-of-another-tree/

 

我们需要借助一个helper方法,这个思想就是双递归,即判断每个大树的节点和小树的根节点的值是否相等,如果相同就进入子树判断方法。否则就在大树节点的左节点和右节点查找。

helper方法中,如果小树为空大树不为空或者两个值不相等,就返回false,如果两个都为空才返回true,否则就继续递归寻找左子树和右子树。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isSubtree(TreeNode s, TreeNode t) {
        if(s == null){
            return false;
        }
        boolean flag = false;
        if(s.val == t.val){
            flag = helper(s.left,t.left) && helper(s.right, t.right);
        }
        return flag?flag:isSubtree(s.left,t) || isSubtree(s.right,t);
    }

    private boolean helper (TreeNode s, TreeNode t){
        if(t == null){
            if(s != null){
                return false;
            }
            return true;
        }
        if(s == null || s.val != t.val){
            return false;
        }
        return helper(s.left,t.left)&&helper(s.right,t.right);
    }
}

 

posted @ 2020-05-07 12:24  ZJPang  阅读(160)  评论(0编辑  收藏  举报