树型递归的总结
面试题26. 树的子结构
首先从A的头节点开始匹配,如果节点值相等,就接着匹配左子树,左子树都相等就匹配右子树
如果A头节点不匹配,就从A的左子树开始匹配....如果左子树不匹配,就从A的右子树开始匹配.....(匹配过程递归执行)
1 class Solution { 2 public boolean isSubStructure(TreeNode A, TreeNode B) { 3 //Leetcode的判定认为 B为空 A空或不空都不匹配 4 if(B == null) return false; 5 //B不为空 A空则不匹配 6 if(A == null) return false; 7 return check(A,B) || isSubStructure(A.left,B) || isSubStructure(A.right,B); 8 } 9 private boolean check(TreeNode A, TreeNode B){ 10 if(B == null) return true; 11 if(A == null || A.val != B.val) return false; 12 return check(A.left,B.left) && check(A.right,B.right); 13 } 14 }
面试题27. 二叉树的镜像
1 class Solution { 2 public TreeNode mirrorTree(TreeNode root) { 3 if(root == null || (root.left == null && root.right == null)) return root; 4 TreeNode temp = root.left; 5 root.left = root.right; 6 root.right = temp; 7 mirrorTree(root.left); 8 mirrorTree(root.right); 9 return root; 10 } 11 }