本题思路:我们可以看到每次其实这个找最大值,然后创建节点的过程就是一个二叉树的前序遍历的过程。所以,我们可以递归来完成它。
注意:分割数组的时候,要注意区间。左闭右开(自己定义)
为了方便对代码的思路有个好的理解。举个例子演示下:
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return tavel(nums,0,nums.length);
}
public TreeNode tavel(int[] nums,int start,int end){
if(start == end){
return null;
}
int index = findMaxIndex(nums,start,end);
int rootValue = nums[index];
TreeNode root = new TreeNode(rootValue);
if(nums.length == 1){
return root;
}
int leftstart = start;
int leftend = index;
int rigthstart = index+1;
int rightend = end;
root.left = tavel(nums,leftstart,leftend);
root.right = tavel(nums,rigthstart,rightend);
return root;
}
public static int findMaxIndex(int[] nums,int start, int end){
int max = nums[start];
int index = start;
for(int i = start + 1; i < end; i++){
if(nums[i] > max){
max = nums[i];
index = i;
}
}
return index;
}
}
本题思路:利用递归来完成。根据题目的描述,可以得到以下内容。我们用前序遍历来完成
class Solution {
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
// 如果两个都为空,直接返回 null
if(root1 == null && root2 == null){
return null;
}
// 两个都不为空或者,一个为空
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;
}
}
本题思路:使用前序遍历,得到目标节点,返回直接返回即可
为了方便理解,画个图来演示下,这个流程。
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
return preorder(root,val);
}
public TreeNode preorder(TreeNode node, int val){
if(node == null){
return null;
}
if(node.val == val){
return node;
}
TreeNode resleft = preorder(node.left,val);
TreeNode resright = preorder(node.right,val);
return resleft == null?resright:resleft;
}
}
本题思路: 二叉搜索树的中序遍历,是有序单调递增的。所以我的思路是,用中序遍历得到一个列表。然后判断是否是单调递增即可
class Solution {
public boolean isValidBST(TreeNode root) {
List<Integer> list = new ArrayList();
inorder(root,list);
for(int i = 1; i < list.size(); i++){
if(list.get(i-1) >= list.get(i)){
return false;
}
}
return true;
}
public void inorder(TreeNode root,List<Integer> list){
if(root == null){
return;
}
inorder(root.left,list);
list.add(root.val);
inorder(root.right,list);
}
}