11.24 log

701.二叉搜索树中的插入操作

class Solution {
public:
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        if(root==NULL){
            TreeNode* node=new TreeNode(val);
            return node;
        }
        if(root->val>val){
            if(root->left){
                insertIntoBST(root->left,val);
            }
            else{
                TreeNode* node=new TreeNode(val);
                root->left=node;
            }
        }
        if(root->valright){
                insertIntoBST(root->right,val);
            }
            else{
                TreeNode* node=new TreeNode(val);
                root->right=node;
            }
        }
        return root;
    }
};

这是比较繁琐的方法,递归参数为根节点,插入值,返回值为插入后的根节点,终止条件为到递归到空节点时,插入节点并返回,递归内部逻辑为如果root值大于val就向左遍历,如果root值小于val就向右遍历,不为空就继续往下,为空就插入节点,最后返回节点

class Solution {
public:
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        if(root==NULL){
            TreeNode* node=new TreeNode(val);
            return node;
        }
        if(root->val>val){
                root->left=insertIntoBST(root->left,val);
        }
        if(root->valright=insertIntoBST(root->right,val);
        }
        return root;
    }
};

这是简化后的方法,用root->left,root->right接住返回回来的node,减少了代码量,代码更简洁

你可能感兴趣的:(算法,leetcode,数据结构)