leetcode 654
题目链接
maximum binary tree,每次根节点均是最大值
思路:
- 和 leetcode 106/105构造二叉树是基本相同的思路
- 每次先找出最大值
max
和其下标maxIndex
- 再划分初始数组进行递归
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
if (nums.length == 0)
return null;
TreeNode root = buildTree(nums, 0, nums.length);
return root;
}
public TreeNode buildTree(int[] nums, int begin, int end) {
if (begin == end)
return null;
int max = -1;
int maxIndex = 0;
for (int i = begin; i < end; ++i) {
if (nums[i] > max) {
max = nums[i];
maxIndex = i;
}
}
TreeNode root = new TreeNode(max);
int leftBegin = begin;
int leftEnd = maxIndex;
int rightBegin = maxIndex + 1;
int rightEnd = end;
root.left = buildTree(nums, leftBegin, leftEnd);
root.right = buildTree(nums, rightBegin, rightEnd);
return root;
}
}
leetcode 617
题目链接
merge 2个二叉树,节点重叠的val
相加
思路:
- 先思考遍历顺序:前序最合适
- 同步遍历2个tree
- 直接改
tree1
的结构,并不构造一个新的二叉树
class Solution {
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if (root1 == null)
return root2;
if (root2 == null)
return root1;
root1.val += root2.val; //middle
root1.left = mergeTrees(root1.left, root2.left); //left
root1.right = mergeTrees(root1.right, root2.right); //right
return root1;
}
}
leetcode 700
题目链接
二叉搜索树相关
思路:
- 二叉搜索树相关概念
left < root.val
,right > root.val
- 递归:
root.val > target
递归找左子树root.val < target
递归找右子树
- 迭代法:
- 二叉搜索树,节点是有序的(普通binary tree迭代法:栈-深度遍历;队列-广度/层次遍历)
- ∴ \therefore ∴搜索路径其实已经规划好了,不需要回溯
1.递归法代码:
class Solution {
TreeNode res;
public TreeNode searchBST(TreeNode root, int val) {
if (root == null)
return null;
if (root.val == val) //middle
res = root;
if (root.val > val)
searchBST(root.left, val);
if (root.val < val)
searchBST(root.right, val);
return res;
}
}
2.迭代法代码
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 if (root.val < val)
root = root.right;
}
return null;
}
}
leetcode 98
题目链接
判断一个tree是否是二叉搜索树
思路:
- 一瞬间想法:中序遍历——是递增序列就是BST
- 递归法:
- 中序遍历
- 处理Middle时,判断当前
node
和他的前一个节点preRoot
(往往是其左孩子)的大小 - 要比较的是左子树所有节点小于中间节点,右子树所有节点大于中间节点
- 迭代法:
- 中序遍历迭代法——用栈
class Solution {
TreeNode preRoot;
public boolean isValidBST(TreeNode root) {
if (root == null)
return true;
boolean left = isValidBST(root.left); //left
if (!left) return false;
if (preRoot != null && preRoot.val >= root.val) //middle
return false;
preRoot = root; //记录前一个节点
boolean right = isValidBST(root.right); //right
return left && right;
}
}