树的子结构
树的子结构
http://www.nowcoder.com/questionTerminal/6e196c44c7004d15b1610b9afca8bd88
一. 思路
若树 B 是树 A 的子结构,则子结构的根节点可能为树 A 的任意一个节点。详情看leetcode题解:面试题26. 树的子结构(先序遍历 + 包含判断,清晰图解)
二. 代码
/** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ class Solution { public boolean HasSubtree(TreeNode A, TreeNode B) { return (A != null && B != null) && (recur(A, B) || HasSubtree(A.left, B) || HasSubtree(A.right, B)); } boolean recur(TreeNode A, TreeNode B) { if(B == null) return true; if(A == null || A.val != B.val) return false; return recur(A.left, B.left) && recur(A.right, B.right); } }