代码随想录第十九章 | 继续二叉树
今天还是二叉树
class Solution { public TreeNode constructMaximumBinaryTree(int[] nums) { int n = nums.length; return maxTree(nums, 0, n - 1); } public TreeNode maxTree(int[] nums, int l, int r){ if(l > r){ return null; } int bond = findMax(nums, l, r); TreeNode root = new TreeNode(nums[bond]); root.left = maxTree(nums, l, bond - 1); root.right = maxTree(nums, bond+ 1, r); return root; } public int findMax(int[] nums, int l, int r){ int max = Integer.MIN_VALUE, maxIndex= l; for(int i = l; i<= r; i++){ if(max < nums[i]){ max = nums[i]; maxIndex = i; } } return maxIndex; } }
递归
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; } }
递归把点相加就好
class Solution { public TreeNode searchBST(TreeNode root, int val) { if(root==null){ return null; } if(root.val == val){ return root; } return root.val > val ? searchBST(root.left, val) : searchBST(root.right,val); } }
非常简单的题,注意是二叉搜索树就好
class Solution { public boolean isValidBST(TreeNode root) { return test(root, Long.MIN_VALUE, Long.MAX_VALUE); } public boolean test(TreeNode node, long min, long max){ if(node == null){ return true; } if(node.val <= min || node.val >=max){ return false; } return test(node.left, min, node.val) && test(node.right, node.val, max); } }
这道题成为中等题的原因就是边界值
今天还是二叉树的一天,二叉树的内容很多很难,很折磨人

浙公网安备 33010602011771号