在二叉查找树中插入节点

来源:互联网 发布:蚌埠市农村金融数据 编辑:程序博客网 时间:2024/06/07 14:24
问题描述:

给定一棵二叉查找树和一个新的树节点,将节点插入到树中。

你需要保证该树仍然是一棵二叉查找树。

样例

给出如下一棵二叉查找树,在插入节点6之后这棵二叉查找树可以是这样的:

  2             2 / \           / \1   4   -->   1   4   /             / \   3             3   6
实现思路:根据二叉查找树的特点,比较要插入的节点的值与根节点的值的大小,若比根节点小,那么利用递归方法在左子树继续寻找合适的插入的位置;否则,在右子树上进行操作。

实现代码:/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
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)
        {
            root=new TreeNode(node->val);
            return root;
        }
        else if(node->val<root->val)
            {
                root->left=insertNode(root->left,node);
                return root;
            }
        else 
            root->right=insertNode(root->right,node);
            return root;
    }
};

做题感想:审完题目,心想就是二叉排序树的插入问题嘛,然后就把课本上的代码打上了,但是没注意到函数的返回类型。

原创粉丝点击