力扣第654题:
记:可以用下标索引来分割数组
代码如下:
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return constructMaximumBinaryTree1(nums, 0, nums.length - 1);
}
public TreeNode constructMaximumBinaryTree1(int[] nums, int left, int right) {
if(left > right) {
return null;
}
if(left == right) {
TreeNode root = new TreeNode(nums[left]);
return root;
}
int mid = left;
for(int i = left; i <= right; i++) {
if(nums[i] > nums[mid]) {
mid = i;
}
}
TreeNode root = new TreeNode(nums[mid]);
root.left = constructMaximumBinaryTree1(nums, left, mid - 1);
root.right = constructMaximumBinaryTree1(nums, mid + 1, right);
return root;
}
}
力扣第617题:
(递归)代码如下:
class Solution {
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
return merge(root1, root2);
}
public TreeNode merge(TreeNode root1, TreeNode root2) {
if(root1 == null) {
return root2;
}
if(root2 == null) {
return root1;
}
root1.val += root2.val;
root1.left = merge(root1.left, root2.left);
root1.right = merge(root1.right, root2.right);
return root1;
}
}
(栈迭代)代码如下:
class Solution {
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if(root1 == null) return root2;
if(root2 == null) return root1;
Stack<TreeNode> stack = new Stack<>();
stack.push(root1);
stack.push(root2);
while(!stack.isEmpty()) {
TreeNode node2 = stack.pop();
TreeNode node1 = stack.pop();
node1.val += node2.val;
if(node1.left != null && node2.left != null) {
stack.push(node1.left);
stack.push(node2.left);
}
if(node1.right != null && node2.right != null) {
stack.push(node1.right);
stack.push(node2.right);
}
if(node1.left == null) node1.left = node2.left;
if(node1.right == null) node1.right = node2.right;
}
return root1;
}
}
力扣第700题:
(迭代)代码如下:
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
while(root != null) {
if(root.val == val) {
return root;
}
if(root.val > val) {
root = root.left;
}else {
root = root.right;
}
}
return null;
}
}
力扣第98题:
(递归)中序遍历,利用二叉搜索树的性质:
class Solution {
long prev = Long.MIN_VALUE;
public boolean isValidBST(TreeNode root) {
if(root == null) return true;
boolean left = isValidBST(root.left);
if(root.val <= prev) return false;
prev = root.val;
boolean right = isValidBST(root.right);
return left && right;
}
}