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;}
}