美文网首页
701. Insert into a Binary Search

701. Insert into a Binary Search

作者: 刘小小gogo | 来源:发表于2018-08-19 17:13 被阅读0次
    image.png

    解法一:递归

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        TreeNode* insertIntoBST(TreeNode* root, int val) {
            if(root == NULL){
                return new TreeNode(val);
            }
            if(val < root->val){
                root->left = insertIntoBST(root->left, val);
            }
            else{
                root->right = insertIntoBST(root->right, val);
            }
            return root;
        }
    };
    

    解法二:迭代
    !!!也很好理解,要注意,当找到合适的位置时,要及时返回。

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        TreeNode* insertIntoBST(TreeNode* root, int val) {
            if(root == NULL) return new TreeNode(val);
            TreeNode* tmp = root;
            while(tmp){
                if(tmp->val > val){
                    if(tmp->left == NULL){
                        tmp->left = new TreeNode(val);
                        return root;
                    }
                    tmp = tmp->left;
                }
                else{
                    if(tmp->right == NULL){
                        tmp->right = new TreeNode(val);
                        return  root;
                    }
                    tmp = tmp->right;
                }
            }
            return root;
        }
    };
    

    相关文章

      网友评论

          本文标题:701. Insert into a Binary Search

          本文链接:https://www.haomeiwen.com/subject/dxnciftx.html