美文网首页
Insert to a binary tree, recursi

Insert to a binary tree, recursi

作者: stepsma | 来源:发表于2018-08-31 00:19 被阅读0次

    Recursive:

    TreeNode* insertIntoBST(TreeNode* root, int val) {
            if(!root){
               return new TreeNode(val);
            }
            
            if(root->val < val){
                root->right = insertIntoBST(root->right, val);
            }
            else{
                root->left = insertIntoBST(root->left, val);
            }
            
            return root;
        }
    

    Iterative:

    TreeNode* insertIntoBST(TreeNode* root, int val) {
            if(!root){
               return new TreeNode(val);
            }
            
            TreeNode *cur = root;
            
            while(cur){
                if(cur->val < val){
                    if(cur->right == NULL){
                        cur->right = new TreeNode(val);
                        break;
                    }
                    else{
                        cur = cur->right;
                    }
                }
                else{
                    if(cur->left == NULL){
                        cur->left = new TreeNode(val);
                        break;
                    }
                    else{
                        cur = cur->left;
                    }
                }
            }
            
            return root;
        }
    

    相关文章

      网友评论

          本文标题:Insert to a binary tree, recursi

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