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;
    }
};

 

posted @ 2018-10-04 16:52  hopskin1  阅读(275)  评论(0编辑  收藏  举报