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

leetcode701. Insert into a Binary Search Tree

www .com earch arch grand com solution clas search

https://www.cnblogs.com/grandyang/p/9914546.html

類似於二分查找的方法,用叠代的方法去做

註意:無論是進入左子樹還是右子樹,左右子樹都變成了新的數,所以需要重新根據root->left = ....來重新生成

class Solution {
public:
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        if(root == NULL)
            return new TreeNode(val);
        if(root->val < val)
            root
->right = insertIntoBST(root->right,val); if(root->val > val) root->left = insertIntoBST(root->left,val); return root; } };

leetcode701. Insert into a Binary Search Tree