剑指 Offer 26. 树的子结构

 

思路:

  先序遍历,递归判断。

  通过先序遍历,先判断B的根节点是否等于A中的一个节点,再从这个节点开始分别判断左子树和右子树是否相同。

代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSubStructure(TreeNode A, TreeNode B) {
        if (B == null || A == null)
            return false;
        return isContain(A, B) || isSubStructure(A.left, B) || isSubStructure(A.right, B);
    }
    boolean isContain(TreeNode A, TreeNode B){
        if (B == null)
            return true;
        if (A == null || A.val != B.val)
            return false;
        return isContain(A.left, B.left) && isContain(A.right, B.right);
    }
}
posted @ 2021-02-23 16:29  zjcfrancis  阅读(40)  评论(0)    收藏  举报