LeetCode 654.最大二叉树
思路并不复杂, 和105,106有相似之处
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| class Solution { public TreeNode constructMaximumBinaryTree(int[] nums) { return counstructMyTree(nums, 0, nums.length); }
private TreeNode counstructMyTree(int[] nums, int startIndex, int endIndex) { if (startIndex >= endIndex) { return null; }
int maxValue = -1; int maxIndex = -1;
for (int i = startIndex; i < endIndex; i++) {
if (nums[i] > maxValue){ maxIndex = i; maxValue = nums[i]; } }
TreeNode root = new TreeNode (maxValue);
root.left = counstructMyTree(nums, startIndex, maxIndex);
root.right = counstructMyTree(nums, maxIndex + 1, endIndex);
return root; } }
|
LeetCode.617 合并二叉树
这道题一开始想复杂了,主要是一开始没想明白递归出口。其实结束递归的条件很清晰,如果一个树为空,那么剩下的分支则无需继续处理。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| 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;
} }
|
LeetCode. 700 二叉搜索树中的搜索
简单题,目的是熟悉二叉搜索树的性质,一颗二叉搜索树的inorder表达一定是单调的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class Solution { public TreeNode searchBSTRecursively(TreeNode root, int val) { if (root == null) return null;
if (root.val == val) { return root; }else if (val > root.val) { return searchBST(root.right, val); }else { return searchBST(root.left, val); } }
public TreeNode searchBST(TreeNode root, int val) { while(root != null) { if(root.val == val) { return root; }else if (root.val < val) { root = root.right; }else { root = root.left; } } return null; }
|
LeetCode 98.验证二叉搜索树
如700所见,一颗树是否为二叉搜索树可以直观的从其中序遍历中体现,这一题便是这一个性质最好的诠释。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| class Solution {
private TreeNode prev;
public boolean isValidBST(TreeNode root) {
if (root == null) { return true; } boolean isLeftValid = isValidBST(root.left);
if (prev != null && prev.val >= root.val) { return false; }
prev = root;
boolean isRightValid = isValidBST(root.right);
return isLeftValid && isRightValid; } }
|