算法修炼Day20|● 654.最大二叉树 ● 617.合并二叉树 ● 700.二叉搜索树中的搜索 ● 98.验证二叉搜索树

37 阅读1分钟
题目:654. 最大二叉树 - 力扣(LeetCode)
思路/想法:

递归:前序遍历

代码实现:
class Solution {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return construct(nums, 0, nums.length);
    }
    private TreeNode construct(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 maxValue = nums[maxIndex];
        for (int i = leftIndex; i < rightIndex; i++) {
            if (nums[i] > maxValue) {
                maxIndex = i;
                maxValue = nums[maxIndex];
            }
        }
        TreeNode root = new TreeNode(maxValue);
        root.left = construct(nums, leftIndex, maxIndex);
        root.right = construct(nums, maxIndex + 1, rightIndex);
        return root;
    }
}
题目:617. 合并二叉树 - 力扣(LeetCode)
思路/想法:

前序遍历

代码实现:
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. 二叉搜索树中的搜索 - 力扣(LeetCode)
思路/想法:

前序遍历

代码实现:
class Solution {
    public TreeNode searchBST(TreeNode root, int val) {
        if (root == null || root.val == val) return root;
        TreeNode left = searchBST(root.left, val);
        if (left != null) return left;
        return searchBST(root.right, val);
    }
}

class Solution {
    public TreeNode searchBST(TreeNode root, int val) {
        if (root == null || root.val == val) return root;
        if (root.val > val) {
            return searchBST(root.left, val);
        } else {
            return searchBST(root.right, val);
        }
    }
}
题目:98. 验证二叉搜索树 - 力扣(LeetCode)
思路/想法:

中序遍历

代码实现:
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;
        // 右
        return isValidBST(root.right);
    }
}