654.最大二叉树
给定一个不重复的整数数组 nums 。 最大二叉树 可以用下面的算法从 nums 递归地构建:
创建一个根节点,其值为 nums 中的最大值。
递归地在最大值 左边 的 子数组前缀上 构建左子树。
递归地在最大值 右边 的 子数组后缀上 构建右子树。
返回 nums 构建的 最大二叉树
就递归,每次找最大值,秒了。
class Solution {int[] nums;public TreeNode constructMaximumBinaryTree(int[] nums) {this.nums = nums;return build(0, nums.length - 1);}public TreeNode build(int left, int right) {if (left > right) {return null;}int index = -1;int max = -1;for (int i = left; i <= right; i++) {if (nums[i] > max) {max = nums[i];index = i;}}TreeNode root = new TreeNode(max);root.left = build(left, index - 1);root.right = build(index + 1, right);return root;}
}
617.合并二叉树
递归,一开始判断节点是否为空(递归停止条件)。
class Solution {public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {if (root1 == null) {return root2;}if (root2 == null) {return root1;}TreeNode root = new TreeNode(root1.val + root2.val);root.left = mergeTrees(root1.left, root2.left);root.right = mergeTrees(root1.right, root2.right);return root;}
}
700.二叉搜索树中的搜索
给定二叉搜索树(BST)的根节点 root 和一个整数值 val。
你需要在 BST 中找到节点值等于 val 的节点。 返回以该节点为根的子树。 如果节点不存在,则返回 null 。
了解BST就能写。
class Solution {public TreeNode searchBST(TreeNode root, int val) {if (root == null) {return null;}if (val == root.val) {return root;}if (val < root.val) {return searchBST(root.left, val);}if (val > root.val) {return searchBST(root.right, val);}return null;}
}