树的子结构
题目:
输入两棵二叉树A和B,判断B是不是A的子结构。
解答:
1 public class Solution { 2 3 public static boolean HashSubTree(TreeNode root1, TreeNode root2) { 4 boolean result = false; 5 6 if(root1 != null && root2 != null) { 7 if(Equal(root1.val, root2.val)) { 8 result = DoesTree1HaveTree2(root1, root2); 9 } 10 11 if(!result) { 12 result = DoesTree1HaveTree2(root1.left, root2); 13 } 14 15 if(!result) { 16 result = DoesTree1HaveTree2(root1.right, root2); 17 } 18 } 19 20 return result; 21 } 22 23 private static boolean Equal(int val1, int val2) { 24 return val1 == val2? true:false; 25 } 26 27 private static boolean DoesTree1HaveTree2(TreeNode root1, TreeNode root2) { 28 if(root2 == null) { 29 return true; 30 } 31 32 if(root1 == null) { 33 return false; 34 } 35 36 if(!Equal(root1.val, root2.val)) { 37 return false; 38 } 39 40 return DoesTree1HaveTree2(root1.left, root2.left) && DoesTree1HaveTree2(root1.right, root2.right); 41 } 42 }
积沙成塔