将有序数组转换为二叉搜索树
思路:
需要注意的关键点有:有序数组、二叉树搜索树(BST)。
因为BST需要高度平衡,左右子树深度相差不超过一,所以第一反应是选择中间元素作为根节点。
如果数组个数为奇数还好,如果数组个数是偶数,那么可以选择中间位置左边或者右边的元素作为根节点。
根节点选取成功之后,可以将中间元素左边所有元素归纳整理为左子树,方法与选取根节点相同。同理,将中间元素右边所有元素归纳整理为右子树。
如此,可以使用递归,那么递归方法的基准条件是什么呢?应该是所有元素都分配完成之后。
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return gen(nums, 0, nums.length - 1);
}
public static TreeNode gen(int[] nums, int left, int right) {
if (left > right) {
return null;
}
int mid = (left + right) / 2;
TreeNode node = new TreeNode(nums[mid]);
node.left = gen(nums, left, mid - 1);
node.right = gen(nums, mid + 1, right);
return node;
}
}
平衡二叉树
思路:
因为平衡二叉树的左子树与右子树的深度相差不超过一,所以可以使用计算二叉树的方法,计算二叉树的方法在之前写过,这里不再赘述。
需要注意的是在递归时,需要判断的条件:
1、左子树与右子树的深度差不超过1。
2、左子树是否是平衡二叉树。
3、右子树是否是平衡二叉树。
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
} else {
return (Math.abs(getDep(root.left) - getDep(root.right)) <= 1) && isBalanced(root.left) && isBalanced(root.right);
}
}
public static int getDep(TreeNode root) {
if (root == null) {
return 0;
} else {
int left = getDep(root.left);
int right = getDep(root.right);
return Math.max(left, right) + 1;
}
}
}
二叉树的最小深度
思路:
二叉树的最小深度与最大深度的思路类似,方法上也是使用递归。在判断条件上,有一定的区别。
1、当根节点为null时,返回0。
2、当左子树为null,右子树不为null,深度值为右子树的深度。
3、同理,当右子树为null,左子树不为null,深度值为左子树的深度。
4、当左子树与右子树均不为null时,最小深度值为左右子树的最小深度。
(这里我的if...else...
用的有点啰嗦,不如官方的简洁,还是头发掉的不够多,功力不够啊)
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
} else if (root.left == null && root.right == null) {
return 1;
} else if (root.left == null && root.right != null) {
return minDepth(root.right) + 1;
} else if (root.left != null && root.right == null) {
return minDepth(root.left) + 1;
} else {
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
}
}
}
今天先到这里~~~