解題思路 :
直接先檢查 root 是否為 nullptr 如果是則回傳 node 不是的話則比較 node 跟 root 的 value 大小:
- node 值較大則 root->right = recursive call (root->right, node) 接著回傳 root
- node 值較小則 root->left = recursive call (root->left, node) 接著回傳 root
C++ code :
<pre><code>
/**
- 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 == nullptr) return node;
if(node->val > root->val){
root->right = insertNode(root->right, node);
return root;
}
root->left = insertNode(root->left, node);
return root;
}
};