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;
}

};

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容