701. Insert into a Binary Search Tree

Posted learning-c

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了701. Insert into a Binary Search Tree相关的知识,希望对你有一定的参考价值。

经典题目:给定一个二叉搜索树,插入一个值为val的新节点

/**
 * 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){
            root=new TreeNode(val);
            return root;
        }
        if(root->val<val){
            root->right=insertIntoBST(root->right,val);
        }else{
            root->left=insertIntoBST(root->left,val);
        }
        return root;
    }
};

 

以上是关于701. Insert into a Binary Search Tree的主要内容,如果未能解决你的问题,请参考以下文章

701. Insert into a Binary Search Tree

[LeetCode] 701. Insert into a Binary Search Tree

leetcode701. Insert into a Binary Search Tree

701. Insert into a Binary Search Tree

Leetcode 701. Insert into a Binary Search Tree

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