其他分享
首页 > 其他分享> > 701.insert-into-a-binary-search-tree 二叉搜索树中的插入操作

701.insert-into-a-binary-search-tree 二叉搜索树中的插入操作

作者:互联网

没啥好说的,但是要注意连续两个ifif... else if之间的区别。

class Solution {
  public:
    TreeNode *insertIntoBST(TreeNode *root, int val) {
        if (root == nullptr) {
            TreeNode *res = new TreeNode(val);
            return res;
        }
        TreeNode *cur = root;
        TreeNode *pre;
        while (cur != nullptr) {
            pre = cur;
            if (val > cur->val)
                cur = cur->right;
            else if (val < cur->val)
                cur = cur->left;
        }
        TreeNode *res = new TreeNode(val);
        if (val > pre->val) {

            pre->right = res;
        } else if (val < pre->val) {

            pre->left = res;
        }
        return root;
    }
};

标签:pre,insert,search,TreeNode,cur,val,binary,res,root
来源: https://www.cnblogs.com/zwyyy456/p/16686999.html