701. Insert into a Binary Search Tree
阿新 • • 發佈:2018-10-04
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