二叉树part5
二叉树part5
654. 最大二叉树 - 力扣(LeetCode)
从中序和后序遍历构造二叉树,以及本题,这类构造树的题目,都是用前序遍历,因为先构造节点,再递归构造左子树和右子树
终止条件,注意一个叶子节点,如果为叶子节点,直接返回就可以
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
if(nums.length == 0){
return null;
}
if(nums.length == 1){ //叶子节点
return new TreeNode(nums[0]);
}
int maxValue = 0;
int index = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] > maxValue){
maxValue = nums[i];
index = i;
}
}
TreeNode cur = new TreeNode(maxValue);
cur.left = constructMaximumBinaryTree(Arrays.copyOfRange(nums, 0, index));
cur.right = constructMaximumBinaryTree(Arrays.copyOfRange(nums, index+1, nums.length));
return cur;
}
}
617. 合并二叉树 - 力扣(LeetCode)
同时操作两个二叉树,跟一个二叉树的递归基本一致
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;
}
}
700. 二叉搜索树中的搜索 - 力扣(LeetCode)
二叉搜索树的定义:
有序性:任意节点的值大于左子树,小于右子树
左右子树也必须是二叉搜索树
性质:
中序遍历结果为升序序列
时间复杂度:
查找、插入、删除:O(log n)
最坏情况: O(n) (退化成链表)
这题真简单
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
if(root == null || root.val == val){
return root;
}
if(val > root.val){
root = searchBST(root.right, val);
}else if(val < root.val){
root = searchBST(root.left, val);
}
return root;
}
}
98. 验证二叉搜索树 - 力扣(LeetCode)
BST有一个中序遍历结果升序的性质,所以这就是坑,比如下面这个树,节点6所在的要求应该是3<x<5

递归不想写,直接中序遍历
class Solution {
List<Integer> arr = new ArrayList<>();
boolean res = true;
public boolean isValidBST(TreeNode root) {
//中序遍历升序序列
preOrder(root);
return res;
}
public void preOrder(TreeNode root){
if(root == null){
return ;
}
preOrder(root.left);
if(arr.size() == 0){
}else if(root.val <= arr.get(arr.size() - 1) && arr.size() != 0){
res = false;
}
arr.add(root.val);
preOrder(root.right);
}
}
浙公网安备 33010602011771号