代码随想录的第十七天(二叉树)
654. 最大二叉树
var constructMaximumBinaryTree = function(nums) {
function buildTree (nums, left, right) {
if (left > right) return null
let maxValue = -1
let maxIndex = -1
for (let i = left; i <= right; i++) {
if (nums[i] > maxValue) {
maxValue = nums[i]
maxIndex = i
}
}
let root = new TreeNode(maxValue)
root.left = buildTree(nums, left, maxIndex - 1)
root.right = buildTree(nums, maxIndex + 1, right)
return root
}
let root = buildTree(nums, 0 , nums.length - 1)
return root
};
思路:
1、确定遍历的函数参数:本身数组肯定是需要传递进去的,还有就是左右两个区间的数组需要往进传或者就是传入进去左右两区间的下标
2、终止条件:就是当区间内的数组为1的时候就代表完成了,或者就是左子树下标高于右子树
3、单层遍历循环:首先肯定需要找出每次的最大值作为当前树的根节点,其次需要定位当前最大值的索引用来区分下一个左右子树的位置,完成遍历
617. 合并二叉树
var mergeTrees = function(root1, 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
};
思路:
1、这道题相对简单,和正常遍历一样只是需要同时遍历两个树
2、参数:就是传入的两个树
3、终止条件:这儿需要注意,当root1为空的时候,这个时候需要返回的是root2,这样才能继续往下遍历,反之就是返回
root1,还有一个隐藏的条件,其实就是当root1和root2都为null时,其实就是返回了null
4、单层递归:获取两个节点的值相加为新的节点,然后去遍历左右子树相同的位置顺序
700. 二叉搜索树中的搜索
var searchBST = function(root, val) {
let root1 = new TreeNode()
let bool = false
const stack = [root]
while (stack.length) {
let size = stack.length
while (size--) {
const cur = stack.shift()
if (cur.val === val) {
root1.val = val
root1.left = cur.left
root1.right = cur.right
bool = true
}
if (cur.left) stack.push(cur.left)
if (cur.right) stack.push(cur.right)
}
}
return bool ? root1 : null
};
思路: 层序遍历就不多说了
var searchBST = function(root, val) {
function getTree (root, val) {
if (root === null) return null
if (root.val === val) {
const root1 = new TreeNode(val)
root1.left = root.left
root1.right = root.right
return root1
}
const left = getTree(root.left, val)
const right = getTree(root.right, val)
if (left) return left
if (right) return right
return null
}
return getTree(root, val)
};
递归:
思路:就是简单的前序遍历,然后搜索到值进行返回
98. 验证二叉搜索树
var isValidBST = function(root) {
const arr = []
function isSearchTree (root) {
if (root) {
isSearchTree(root.left)
arr.push(root.val)
isSearchTree(root.right)
}
}
isSearchTree(root)
for (let i = 1; i < arr.length; i++) {
if (arr[i-1] >= arr[i]) {
return false
}
}
return true
};
思路:
1、辅助数组:其实就是中序遍历的时候将所有的节点放入数组,这个数组应该是递增的,如果符合就是二叉搜索树
var isValidBST = function(root) {
let maxVal = null
function inOrder (root) {
if (root === null) return true
let left = inOrder(root.left)
if (maxVal !== null && maxVal.val >= root.val) return false
maxVal = root
let right = inOrder(root.right)
return left && right
}
return inOrder(root)
};
递归思路:
1、确定传入参数:树形
2、确定终止条件:就是当遍历到根节点或者就是中途有不符合条件的就终止
3、单层递归:就是中序遍历,中序遍历是递增的,所以他的前一个节点的数值肯定要小于当前节点的数值才正确
注意:二叉搜索树是所有的左子树节点都要小于中间节点