1. 程式人生 > >701. Insert into a Binary Search Tree

701. Insert into a Binary Search Tree

nbsp pre arch nod oot 二叉 def class truct

經典題目:給定一個二叉搜索樹,插入一個值為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