Insert Node in a Binary Search Tree

Insert Node in a Binary Search Tree.png

解題思路 :

直接先檢查 root 是否為 nullptr 如果是則回傳 node 不是的話則比較 node 跟 root 的 value 大小:

  1. node 值較大則 root->right = recursive call (root->right, node) 接著回傳 root
  2. 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;
}

};

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容