🚅【leetcode】701. 二叉搜索树中的插入操作

🚀题目
leetcode原题链接
💥leetcode代码模板
/**
* 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 insertIntoBST = function(root, val) {
};
🚀思路
val < root.val
,则val
应该插入到左子树中,递归左子树并拿到返回值
let node = insertIntoBST(root.left , val)
判断返回值是否为null
,不为null就把它作为当前节点的左节点
if(node) root.left = node
val > root.val
则val
应该插入到右子树中,递归右子树并拿到返回值
let node = insertIntoBST(root.right , val)
判断返回值是否为null
,不为null就把它作为当前节点的右节点
if(node) root.right = node
💻代码
var insertIntoBST = function(root, val) {
if(!root) return new TreeNode(val)
if(val < root.val){
let node = insertIntoBST(root.left , val)
if(node) root.left = node
}
else{
let node = insertIntoBST(root.right , val)
if(node) root.right = node
}
return root
};
🍪总结
利用二叉搜索树的特点沿一条明确的路径遍历下去,遇到空节点就把要插入到值放到该空节点的位置,然后再沿路径返回即可。