题1:树的高度(Maximum Depth of Binary Tree)
LeetCode题号:104
难度:easy
链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/description/
题目描述:
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
代码:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public int maxDepth(TreeNode root) { 12 if (root == null) return 0; 13 return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; 14 } 15 }
分析:
maxDepth(root.left)表示计算当前节点左子树的高度,maxDepth(root.right)表示计算当前节点右子树的高度,取二者较大值,再加1(根节点)即为树的最大深度。
题2:平衡树(Balanced Binary Tree)
LeetCode题号:110
难度:easy
链接:https://leetcode-cn.com/problems/balanced-binary-tree/description/
题目描述:
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
示例 1:给定二叉树 [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回 true 。
示例 2:给定二叉树 [1,2,2,3,3,null,null,4,4]
1
/ \
2 2
/ \
3 3
/ \
4 4
返回 false 。
代码:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 private boolean result = true; 12 13 public boolean isBalanced(TreeNode root) { 14 maxDepth(root); 15 return result; 16 } 17 18 public int maxDepth(TreeNode root) { 19 if (root == null) return 0; 20 int l = maxDepth(root.left); 21 int r = maxDepth(root.right); 22 if (Math.abs(l - r) > 1) result = false; 23 return 1 + Math.max(l, r); 24 } 25 }
分析:
主判断方法为isBalanced(),其中调用了maxDepth()
maxDepth()方法中,我们通过递归,计算了每个节点的左后子树的深度并进行比较,若差距大于1,则将result置为false(不平衡)
题3:两节点的最长路径(Diameter of Binary Tree)
LeetCode题号:543
难度:easy
链接:https://leetcode-cn.com/problems/diameter-of-binary-tree/description/
题目描述:
给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。
示例 :给定二叉树
1
/ \
2 3
/ \
4 5
返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。
注意:两结点之间的路径长度是以它们之间边的数目表示。