654.最大二叉树
如果只有一个值,创建这个节点并且返回。
找到最大值以及索引。创建节点,根据索引递归左右子树。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return construct(nums, 0, nums.length);
}
private TreeNode construct(int[] nums, int leftEdge, int rightEdge){
if(rightEdge - leftEdge == 1){
TreeNode cur = new TreeNode(nums[leftEdge]);
return cur;
}
int maxIndex = leftEdge;
int maxValue = nums[leftEdge];
for(int i = leftEdge;i < rightEdge; i++){
if(maxValue < nums[i]){
maxValue = nums[i];
maxIndex = i;
}
}
TreeNode root = new TreeNode(maxValue);
if(maxIndex - leftEdge >= 1){
root.left = construct(nums,leftEdge, maxIndex);
}
if(rightEdge - maxIndex > 1){
root.right = construct(nums,maxIndex+1, rightEdge);
}
return root;
}
}
617.合并二叉树
可以创建一颗新的树,下面代码是在tree1上直接操作。如果遍历到节点是空,则该节点不会再又子树了,直接返回另一棵树,如果另一颗树也为空,那返回的哪个节点都一样。
两个节点数值相加。递归左右子树。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
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.二叉搜索树中的搜索
搜索树有顺序。递归结束条件是节点为空了。或者找到遍历值了。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
if(root == null || root.val == val) return root;
TreeNode res = null;
if(root.val < val){
res = searchBST(root.right, val);
}
if(root.val > val){
res = searchBST(root.left, val);
}
return res;
}
}
98.验证二叉搜索树
思路:用双指针,pre指针一定比cur指针小。
class Solution {
public TreeNode pre = null;
public boolean isValidBST(TreeNode root) {
if(root == null ) return true;
boolean left = isValidBST(root.left);
if(pre != null && root.val <= pre.val){
return false;
}
pre = root;
boolean right = isValidBST(root.right);
return left && right;
}
}