1. 树的高度2. 平衡树3. 两节点的最长路径4. 翻转树5. 合并两棵树6. 判断路径和是否即是一个数7. 统计路径和即是一个数的路径数量8. 子树9. 树的对称10. 最小路径11. 统计左叶子节点的和12. 相同节点值的最大路径长度13. 距离遍历14. 找出二叉树中第二小的节点接待关注笔者,优质文章都在这里等你。递归一棵树要么是空树,要么有两个指针,每个指针指向一棵树。
树是一种递归结构,许多树的问题可以使用递归来处置惩罚。1. 树的高度104. Maximum Depth of Binary Tree (Easy)public int maxDepth(TreeNode root) { if (root == null) return 0; return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;}2. 平衡树110. Balanced Binary Tree (Easy) 3 / \ 9 20 / \ 15 7平衡树左右子树高度差都小于即是 1private boolean result = true;public boolean isBalanced(TreeNode root) { maxDepth(root); return result;}public int maxDepth(TreeNode root) { if (root == null) return 0; int l = maxDepth(root.left); int r = maxDepth(root.right); if (Math.abs(l - r) > 1) result = false; return 1 + Math.max(l, r);}3. 两节点的最长路径543. Diameter of Binary Tree (Easy)Input: 1 / \ 2 3 / \ 4 5Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].private int max = 0;public int diameterOfBinaryTree(TreeNode root) { depth(root); return max;}private int depth(TreeNode root) { if (root == null) return 0; int leftDepth = depth(root.left); int rightDepth = depth(root.right); max = Math.max(max, leftDepth + rightDepth); return Math.max(leftDepth, rightDepth) + 1;}4. 翻转树226. Invert Binary Tree (Easy)public TreeNode invertTree(TreeNode root) { if (root == null) return null; TreeNode left = root.left; // 后面的操作会改变 left 指针,因此先生存下来 root.left = invertTree(root.right); root.right = invertTree(left); return root;}5. 合并两棵树617. Merge Two Binary Trees (Easy)Input: Tree 1 Tree 2 1 2 / \ / \ 3 2 1 3 / \ \ 5 4 7Output: 3 / \ 4 5 / \ \ 5 4 7public TreeNode mergeTrees(TreeNode t1, TreeNode t2) { if (t1 == null && t2 == null) return null; if (t1 == null) return t2; if (t2 == null) return t1; TreeNode root = new TreeNode(t1.val + t2.val); root.left = mergeTrees(t1.left, t2.left); root.right = mergeTrees(t1.right, t2.right); return root;}6. 判断路径和是否即是一个数Leetcdoe : 112. Path Sum (Easy)Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.路径和界说为从 root 到 leaf 的所有节点的和。public boolean hasPathSum(TreeNode root, int sum) { if (root == null) return false; if (root.left == null && root.。
本文来源:亚搏手机版app下载体育官网-www.nbpengtai.com