演算法題(三十八):判斷樹的子結構
阿新 • • 發佈:2018-11-24
題目描述
輸入兩棵二叉樹A,B,判斷B是不是A的子結構。(ps:我們約定空樹不是任意一個樹的子結構)
分析
從A樹根結點開始遍歷,如果結點與B樹結點相等,則遞迴判斷左子結點和右子結點的情況;若不等,則往下遍歷A樹左右結點各自與B樹的情況。
已AC
程式碼
public class ChildTree { public static boolean HasSubtree(TreeNode root1, TreeNode root2){ if (root1 == null || root2 == null) return false; return fun(root1, root2) || HasSubtree(root1.left, root2)||HasSubtree(root1.right, root2); } public static boolean fun(TreeNode root1, TreeNode root2){ if(root1 == null){ return root2==null; } if(root2 == null){ return true; } if(root1.val == root2.val){ return fun(root1.left, root2.left) && fun(root1.right, root2.right); } return false; } }