二叉搜索树的递归和非递归的插入方法

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
 #include<stack>
class Solution {
public:
    /**
     * @param root: The root of the binary search tree.
     * @param node: insert this node into the binary search tree
     * @return: The root of the new binary search tree.
     */
     /*
    TreeNode* insertNode(TreeNode* root, TreeNode* node) {
        // write your code here
        if(root==NULL)
            return node;
        else
        {
            if(node->val<root->val)
                root->left=insertNode(root->left,node);
            else
                root->right=insertNode(root->right,node);
            return root;
        }
    }
    */
    
    TreeNode* insertNode(TreeNode* root, TreeNode* node) {
        TreeNode *roottmp=root;
        TreeNode* rootpre=root;
        if(root==NULL)
        return node;
        while(root)
        {
            rootpre=root;
            if(root->val>node->val)
            {
                
                root=root->left;
                if(root==NULL)
                {
                    rootpre->left=node;
                    return roottmp;
                }
                
            }
            else
            {
                root=root->right;
                if(root==NULL)
                {
                    rootpre->right=node;
                    return roottmp;
                }
            }
        }
        
        
        
    }
};

  

posted @ 2016-07-04 21:14  simple_wxl  阅读(1355)  评论(0编辑  收藏  举报