[编程题]树的子结构
树的子结构
http://www.nowcoder.com/questionTerminal/6e196c44c7004d15b1610b9afca8bd88
/** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ /* 递归运算 注意各个if条件语句的先后顺序 */ public class Solution { public boolean HasSubtree(TreeNode root1,TreeNode root2) { boolean result=false; //递归终止条件 if(root1!=null&&root2!=null){ //判断树1与树2的头结点相等吗 if(root1.val==root2.val){ result=subtreeIsEqual(root1,root2); } if(!result){ //判断树1的左子树与树2的子树相等吗 result=HasSubtree(root1.left,root2); } if(!result){ //判断树1的右子树与树2的子树相等吗 result=HasSubtree(root1.right,root2); } } return result; } public boolean subtreeIsEqual(TreeNode subroot1,TreeNode subroot2){ //递归终止条件 //先判断树2为空吗,因为subtreeIsEqual执行的条件是父节点的值分别相等 if(subroot2==null){ return true; } //再判断树1为空吗 if(subroot1==null){ return false; } //判断根节点 if(subroot1.val!=subroot2.val){ return false; }else{ return subtreeIsEqual(subroot1.left,subroot2.left)&&subtreeIsEqual (subroot1.right,subroot2.right); } } }