链接力扣654-最大二叉树
思路
class Solution {public TreeNode constructMaximumBinaryTree(int[] nums) {return getRoot(nums,0,nums.length);}public TreeNode getRoot(int[] nums,int leftIndex,int rightIndex){// 已经没有节点if(rightIndex - leftIndex < 1) return null;// 这段定义了左闭右开的意义if(rightIndex - leftIndex == 1) return new TreeNode(nums[leftIndex]);// 找到最大值、最大值的索引保存下来int maxIndex = leftIndex;int maxVal = nums[maxIndex];// for循环范围是本棵树,不是整个数组的长度for(int i = leftIndex + 1; i < rightIndex; i++){if(nums[i] > maxVal){maxVal = nums[i];maxIndex = i;}}// 根据最大值构建根节点TreeNode root = new TreeNode(maxVal);// 根据最大值索引、左闭右开原则来构建左右子树root.left = getRoot(nums,leftIndex,maxIndex);root.right = getRoot(nums,maxIndex+1,rightIndex);return root;}
}
链接力扣617-合并二叉树
思路
class Solution {public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {// 两棵树为空的情况考虑了if(root1 == null) return root2;if(root2 == null) return root1;// 为了不使用新空间,将root1作为返回树root1.val = root1.val + root2.val;root1.left = mergeTrees(root1.left,root2.left);root1.right = mergeTrees(root1.right,root2.right);return root1;}
}
链接力扣700-二叉搜索树中的搜索
思路
class Solution {public TreeNode searchBST(TreeNode root, int val) {if(root == null) return null;if(root.val == val) return root;if(root.val > val) return searchBST(root.left,val);if(root.val < val) return searchBST(root.right,val);return null;}
}
链接力扣98-验证二叉搜索树
思路
class Solution {// 递归// 记录上一个节点TreeNode pre;public boolean isValidBST(TreeNode root) {if (root == null) return true;// 左boolean left = isValidBST(root.left);// 中:前一个节点不为空的情况下大于了root,则返回falseif (pre != null && root.val <= pre.val) {return false;}pre = root;// 右boolean right = isValidBST(root.right);return right&&left;}
}