Leetcode 654.最大二叉树
题目:654.最大二叉树
初始思路
和根据前(后)序和中序遍历构建二叉树一样,都是找到根节点,然后递归建立树。
代码
var constructMaximumBinaryTree = function (nums) {const BuildTree = (arr, left, right) => {if (left > right) {return null}// 找到数组中的最大值和对应的下标,构建这部分的根节点let maxValue = -1let maxIndex = -1for (let i = left; i <= right; i++) {if (arr[i] > maxValue) {maxValue = arr[i]maxIndex = i}}let root = new TreeNode(maxValue)// 从maxIndex这里进行分割root.left = BuildTree(arr, left, maxIndex - 1)root.right = BuildTree(arr, maxIndex + 1, right)return root}let root = BuildTree(nums, 0, nums.length - 1)return root};
感想
- 思路挺简单的,也挺常规,就是代码要好好写。
Leetcode 617.合并二叉树
题目:617.合并二叉树
初始思路
代码
var mergeTrees = function (root1, root2) {const preOrder = (root1, root2) => {if (!root1) return root2if (!root2) return root1root1.val += root2.valroot1.left = preOrder(root1.left, root2.left)root1.right = preOrder(root1.right, root2.right)return root1}return preOrder(root1, root2)}
var mergeTrees = function (root1, root2) {if (!root1) return root2if (!root2) return root1// 规定以root1为基准进行修改let queue = []queue.push(root1)queue.push(root2)while (queue.length) {let node1 = queue.shift()let node2 = queue.shift()node1.val += node2.valif (node1.left != null && node2.left != null) {queue.push(node1.left)queue.push(node2.left)}if (node1.right != null && node2.right != null) {queue.push(node1.right)queue.push(node2.right)}if (node1.left == null && node2.left != null) {node1.left = node2.left}if (node1.right == null && node2.right != null) {node1.right = node2.right}}return root1};
感想
- 递归也简单,为什么我的第一反应是用层序遍历。
Leetcode 700.二叉搜索树中的搜索
初始思路
代码
var searchBST = function (root, val) {if (!root || root.val === val) {return root}else if (root.val > val) {// 在左子树中继续找return searchBST(root.left, val)} else if (root.val < val) {// 在右子树中继续找return searchBST(root.right, val)}};
var searchBST = function (root, val) {while (!root) {if (root.val > val) {root = root.left} else if (root.val < val) {root = root.right} else {return root}}return null}
感想
- 复习一下二叉搜索树的定义。
- 二叉搜索树:
- 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
- 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
- 它的左、右子树也分别为二叉排序树
Leetcode 98.验证二叉搜索树
题目:98.验证二叉搜索树
初始思路
代码
var isValidBST = function (root) {let arr = []const buildArr = (root) => {if (root) {// 前 中 后buildArr(root.left)arr.push(root.val)buildArr(root.right)}}buildArr(root)for (let i = 1; i < arr.length; i++){if (arr[i] <= arr[i - 1]) {return false}}return true};
感想
- 递归中序遍历将二叉搜索树转变成一个数组,然后判断这个数组是否有序。利用了二叉搜索树的特性。
