思路和由中后序列构建树的思路是一样的,只不过这里不是通过后序的最后一个数来进行分割,而是通过找最大值进行分割左右子树
迭代找出左子树和右子树的的边界,返回当前节点就行了
具体代码后续补
这里的return node不能到最后才去return,一定在某一个条件里面马上return了
javascript
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root1
* @param {TreeNode} root2
* @return {TreeNode}
*/
var mergeTrees = function(root1, root2) {
// console.log(root1,root2);
// console.log(root1 === null)
// return;
//两个都为空
if(root1 == null && root2 == null) return null;
//root2为空
let node = new TreeNode();
if(root1 != null && root2 == null){
let node = new TreeNode(root1.val);
node.left = mergeTrees(root1.left, null);
node.right = mergeTrees(root1.right, null);
return node;
}else if(root1 == null && root2 != null){
let node = new TreeNode(root2.val);
node.left = mergeTrees(null, root2.left);
node.right = mergeTrees(null, root2.right);
return node;
}else{
let node = new TreeNode(root1.val + root2.val);
node.left = mergeTrees(root1.left, root2.left);
node.right = mergeTrees(root1.right, root2.right);
return node;
}
};
javascript
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} val
* @return {TreeNode}
*/
var searchBST = function(root, val) {
if(!root) return null;
if(val > root.val){
return searchBST(root.right, val);
}else if(val < root.val){
return searchBST(root.left, val);
}else return root;
};
这道题有陷阱的,子树是BST,不代表这个树一定是BST
要清楚的特性是对于BST来说,起中序遍历的数组一定是一个升序数组
javascript
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
var isValidBST = function(root) {
let inorder = [];
inOrder(root, inorder);
for(let i = 1; i < inorder.length; i++){
if(inorder[i - 1] >= inorder[i]) return false;
}
return true;
};
function inOrder(root, inorder){
if(!root) return;
inOrder(root.left, inorder);
inorder.push(root.val);
inOrder(root.right, inorder);
}