1、111. Minimum Depth of Binary Tree
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
分析:在树的题目中,经常要用的递归形式之一是对左子树递归(并返回值),对右子树递归(并返回值),然后对两者(的返回值)进行处理得到当前根节点对应的结果。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
if(root == null) return 0;
int left = minDepth(root.left);
int right = minDepth(root.right);
return (left == 0 || right == 0) ? left + right + 1 : Math.min(left, right) + 1;
}
}
2、110. Balanced Binary Tree
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
分析:树的递归经常用到两种思路,一种是top down,自顶向下依次判断,但是这样会存在对孩子节点的重复遍历;另一种是bottom up,对每个节点只遍历一次,可以大大减少复杂度。
解法1:top down。时间复杂度O(N^2)。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
int left = height(root.left);
int right = height(root.right);
return Math.abs(left-right) <= 1 && isBalanced(root.left) && isBalanced(root.right);
}
private int height(TreeNode root) {
if(root == null) return 0;
int left = height(root.left);
int right = height(root.right);
return Math.max(left, right) + 1;
}
}
解法2:bottom up。时间复杂度O(N)。当树不平衡是返回-1,当树平衡时返回根节点的高度。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isBalanced(TreeNode root) {
return height(root) != -1;
}
private int height(TreeNode root) {
if(root == null) return 0;
int left = height(root.left);
if(left == -1) return -1;
int right = height(root.right);
if(right == -1) return -1;
if(Math.abs(left-right) > 1) return -1;
return Math.max(left, right) + 1;
}
}
3、108. Convert Sorted Array to Binary Search Tree
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
分析:对于这种数组递归,常用的做法是在递归函数的参数中传入要处理的部分数组起始下标,这样可以避免新建数组,节约空间。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if(nums == null) return null;
return helper(nums, 0, nums.length - 1);
}
private TreeNode helper(int[] nums, int start, int end) {
if(start > end) return null;
int mid = (start + end) >> 1;
TreeNode root = new TreeNode(nums[mid]);
root.left = helper(nums, start, mid - 1);
root.right = helper(nums, mid + 1, end);
return root;
}
}