题解 | #树的子结构#
树的子结构
http://www.nowcoder.com/practice/6e196c44c7004d15b1610b9afca8bd88
这道题其实不难,但是我一直在纠结
{8,8,#,9,#,2,#,5},{8,9,#,2}
是怎么个树结构?
原来是:
8 8 # 9 # 2 # 5
解题思路就是利用递归,坑点就是注意null值的判断,直接看下面代码吧,比较简单。
/** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { public boolean HasSubtree(TreeNode root1,TreeNode root2) { if (root2 == null || root1 == null) { return false; } if (root1.val == root2.val) { boolean leftSame = false; if (root2.left == null) { leftSame = true; } else { leftSame = HasSubtree(root1.left, root2.left); } boolean rightSame = false; if (root2.right == null) { rightSame = true; } else { rightSame = HasSubtree(root1.right, root2.right); } if (leftSame && rightSame) { return true; } } return HasSubtree(root1.left, root2) || HasSubtree(root1.right, root2); } }