Leetcode 654. 最大二叉树
题目链接:654. 最大二叉树
构造二叉树类的题目,一般采用的是前序遍历,先构造中间节点,然后递归构造左子树和右子树。
这道题目其实和 “Leetcode 106.从中序与后序遍历序列构造二叉树” 是一个思路。
注意类似用数组构造二叉树的题目,每次分隔尽量不要定义新的数组,而是通过下标索引直接在原数组上操作,这样可以节约时间和空间上的开销。
解题:成功
(弄懂 Leetcode 106,这道题就很简单了)
代码实现
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return dfs(nums, 0, nums.length);
}
public TreeNode dfs(int[] nums, int start, int end){
if(start >= end){
return null;
}
if(end - start == 1){
return new TreeNode(nums[start]);
}
int maxIndex = start;
int max = nums[maxIndex];
for(int i = start + 1; i < end; i++){
if(nums[i] > max){
maxIndex = i;
max = nums[i];
}
}
TreeNode root = new TreeNode(max);
int leftStart = start;
int leftEnd = maxIndex;
int rightStart = maxIndex + 1;
int rightEnd = end;
root.left = dfs(nums, leftStart, leftEnd);
root.right = dfs(nums, rightStart, rightEnd);
return root;
}
}
Leetcode 617. 合并二叉树
题目链接:617. 合并二叉树
操作两棵二叉树的题目。之前在“Leetcode 101. 对称二叉树“中也一起操作了两棵二叉树。
代码实现
class Solution {
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if(root1 == null){
return root2;
}
if(root2 == null){
return root1;
}
root1.val += root2.val;
root1.left = mergeTrees(root1.left, root2.left);
root1.right = mergeTrees(root1.right, root2.right);
return root1;
}
}
Leetcode 700. 二叉搜索树中的搜索
题目链接:700. 二叉搜索树中的搜索
因为二叉搜索树的有序性,遍历的时候要比普通二叉树简单很多。对于一般二叉树,递归过程中还有回溯的过程,例如走一个左方向的分支走到头了,那么要调头,在走右分支。而对于二叉搜索树,不需要回溯的过程,因为节点的有序性就帮我们确定了搜索的方向。
一提到二叉树遍历的迭代法,可能立刻想起使用栈来模拟深度遍历,使用队列来模拟广度遍历。对于二叉搜索树可就不一样了,因为二叉搜索树的特殊性,也就是节点的有序性,可以不使用辅助栈或者队列就可以写出迭代法。
所以针对二叉搜索树的题目,一样要利用其特性。
代码实现(递归)
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
if(root == null || root.val == val){
return root;
}
if(val < root.val){
return searchBST(root.left, val);
}
else{
return searchBST(root.right, val);
}
}
}
代码实现(迭代)
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
while(root != null){
if(root.val == val){
return root;
}
if(val < root.val){
root = root.left;
}
else{
root = root.right;
}
}
return null;
}
}
Leetcode 98. 验证二叉搜索树
题目链接:98. 验证二叉搜索树
遇到搜索树,一定想着中序遍历,这样才能利用上特性。
中序遍历下,输出的二叉搜索树节点的数值是有序序列。有了这个特性,验证二叉搜索树,就相当于变成了判断一个序列是不是递增的了。
class Solution {
TreeNode pre = null;
public boolean isValidBST(TreeNode root) {
if(root == null){
return true;
}
boolean left = isValidBST(root.left);
if(!left){
return false;
}
if(pre != null && root.val <= pre.val){
return false;
}
pre = root;
boolean right = isValidBST(root.right);
return right;
}
}