2024/8/30 LeetCode Hot100 binaryTree

This commit is contained in:
Cool 2024-08-31 01:12:56 +08:00
parent c92ea90fbb
commit 3839cde010
2 changed files with 62 additions and 8 deletions

View File

@ -17,16 +17,23 @@ public class Num108 {
}
public TreeNode buildTree(int[] nums, int start, int end) {
if(start>=end) return null;
TreeNode node=new TreeNode();
int index=(start+end)/2;
node.val=nums[index];
node.left=buildTree(nums,start,index-1);
node.right=buildTree(nums,index+1,end);
if (start > end) return null;
if(start==end) return new TreeNode(nums[start]);
TreeNode node = new TreeNode();
if(end-start<2){
node.val=nums[end];
node.left= new TreeNode(nums[start]);
return node;
}
int index = (start + end) / 2;
node.val = nums[index];
node.left = buildTree(nums, start, index - 1);
node.right = buildTree(nums, index + 1, end);
return node;
}
@Test
public void test(){
sortedArrayToBST(new int[]{-10,-3,0,5,9});
public void test() {
sortedArrayToBST(new int[]{-10, -3, 0, 5, 9});
}
}

View File

@ -0,0 +1,47 @@
package com.cool.hot100.binary_tree;
import java.util.ArrayList;
import java.util.List;
/**
* Created with IntelliJ IDEA.
*
* @Author: Cool
* @Date: 2024/08/31/0:03
* DayNumber 2
* Hard 2
* Level 3
*/
public class Num98 {
public boolean isValidBST(TreeNode root) {
if (root == null) return true;
return isValidBST(root,Long.MIN_VALUE,Long.MAX_VALUE);
// List<Integer> list = new ArrayList<>();
// validBST(root, list);
// for (int i = 0; i < list.size() - 1; i++) {
// if (list.get(i) >= list.get(i + 1)) return false;
// }
// return true;
}
//解法1 中序遍历比较
public void validBST(TreeNode root, List<Integer> list) {
if (root == null) return;
validBST(root.left, list);
list.add(root.val);
validBST(root.right, list);
}
//解法2
public boolean isValidBST(TreeNode root, long start, long end) {
if(root==null)return true;
if(root.val>start&&root.val<end){
return isValidBST(root.left,start,root.val)&&isValidBST(root.right,root.val,end);
}
return false;
}
}