654. Maximum Binary Tree
- 思路
- 前序遍历
- 造树一般都用前序,因为要先确认中结点
-
java class Solution { public TreeNode constructMaximumBinaryTree(int[] nums) { TreeNode node = new TreeNode(); //这里终止条件设置的是数组中只有一个元素 if(nums.length == 1){ node.val = nums[0]; return node; } int maxVal = 0; int maxIndex = 0; //中 for (int i =0; i< nums.length; i++){ if (nums[i] > maxVal){ maxVal = nums[i]; maxIndex = i; } } node.val = maxVal; //左 if(maxIndex > 0 ){ int[] newArr = Arrays.copyOfRange(nums, 0, maxIndex); node.left = constructMaximumBinaryTree(newArr); } //右 if( maxIndex + 1 < nums.length){ int[] newArr = Arrays.copyOfRange(nums, maxIndex + 1, nums.length); node.right = constructMaximumBinaryTree(newArr); } return node; } }
- 前序遍历
617. Merge Two Binary Trees
- 思路
- 直接延用tree1的结构,前序遍历
-
java class Solution { public TreeNode mergeTrees(TreeNode root1, TreeNode root2) { if (root1 == null){ return root2; } if (root2 == null){ return root1; } root1.val = root1.val + root2.val; //中 root1.left = mergeTrees(root1.left, root2.left); //左 root1.right = mergeTrees(root1.right, root2.right); //右 return root1; } }
98. Validate Binary Search Tree
- 思路
- 中序遍历
- BST的 inorder traverse 结果是单调递增的
-
java class Solution { TreeNode max; public boolean isValidBST(TreeNode root) { if (root == null){ return true; } boolean left = isValidBST(root.left); if(!left){ return false; } if(max!=null && root.val
迭代法
迭代法跟中序遍历模板几乎一致,就是中结点不是res.add了而已
-
class Solution { public boolean isValidBST(TreeNode root) { if (root == null){ return true; } StackTreeNode> stack = new Stack<>; TreeNode pre == null; while(root != null || !stack.isEmpty()){ while(root != null){ stack.push(root); root = root.left; } TreeNode temp = stack.pop(); if(pre != null && pre >= temp){ return false; } pre = temp; root = root.right; } return true } }
- 中序遍历