lintcode insert-node-in-a-binary-search-tree 在二叉查找树中插入节点

来源:互联网 发布:h5页面分享到朋友圈js 编辑:程序博客网 时间:2024/06/08 10:22

问题描述

http://www.lintcode.com/zh-cn/problem/insert-node-in-a-binary-search-tree/

笔记

当root节点为空,表示可以插入node,因此直接返回node。
如果node->val < root->val,应该在左子树插入。否则在右子树插入。然后返回root。

代码

/** * 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)            return node;        if (node->val < root->val)        {            root->left = insertNode(root->left, node);            return root;        }        root->right = insertNode(root->right, node);        return root;    }};
0 0
原创粉丝点击