遍历数组,找到数组中最大的元素及其下标,新建一个节点,val为当前数组范围最大元素。以数组最大元素下标为节点分割左右数组,递归遍历
/**
* 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 constructMaximumBinaryTree(nums, 0, nums.length);
}
public TreeNode constructMaximumBinaryTree(int[] nums, int begin, int end) {
// 没有元素
if (end - begin < 1) {
return null;
}
// 只有一个元素
if (end - begin == 1) {
return new TreeNode(nums[begin]);
}
int maxIndex = begin;
int maxValue = nums[begin];
for (int i = begin + 1; i < end; i++) {
if (nums[i] > maxValue) {
maxIndex = i;
maxValue = nums[i];
}
}
TreeNode root = new TreeNode(maxValue);
// 根据maxIndex划分左右子树
root.left = constructMaximumBinaryTree(nums, begin, maxIndex);
root.right = constructMaximumBinaryTree(nums, maxIndex + 1, end);
return root;
}
}
以root1为最终合并后的二叉树,前序遍历,root1节点为null返回root2节点,root2节点为null返回root1节点。
/**
* 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;
}
}
利用二叉搜索树特性,若val大于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 searchBST(TreeNode root, int val) {
if (root == null || root.val == val) {
return root;
}
TreeNode result = null;
if (root.val > val) {
result = searchBST(root.left, val);
}
if (root.val < val) {
result = searchBST(root.right, val);
}
return result;
}
}
二叉搜索树中序遍历后为一个递增的数据,注意不能简单判断当前节点大于左节点、当前节点大于右节点。利用中序遍历,判断当前节点大于前一个节点
/**
* 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 {
TreeNode max;
public boolean isValidBST(TreeNode root) {
if (root == null) {
return true;
}
boolean left = isValidBST(root.left);
if (!left) {
return false;
}
if (max != null && root.val <= max.val) {
return false;
}
max = root;
boolean right = isValidBST(root.right);
return right;
}
}