题目链接:最大二叉树Ⅱ
同链接:654. 最大二叉树
root.val<val root放B的左子树,否则给的节点在A的右子树中,即遍历右子树找到一个比它小的树放在左子树即可。
/**
* 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 insertIntoMaxTree(TreeNode root, int val) {
if(root == null || root.val < val) {
TreeNode tmp = new TreeNode(val);
tmp.left = root;
return tmp;
}
root.right = insertIntoMaxTree(root.right, val);
return root;
}
}
/**
* 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 buildTree(nums, 0, nums.length - 1);
}
private TreeNode buildTree(int[] nums, int lo, int hi) {
if (lo > hi) return null;
int index = lo;
for (int i = lo + 1; i <= hi; i++) {
if (nums[i] > nums[index]) {
index = i;
}
}
TreeNode root = new TreeNode(nums[index]);
root.left = buildTree(nums, lo, index - 1);
root.right = buildTree(nums, index + 1, hi);
return root;
}
}