问题描述
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;
}
};