美文网首页
Insert Node in a Binary Search T

Insert Node in a Binary Search T

作者: 一枚煎餅 | 来源:发表于2016-09-19 08:42 被阅读0次
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;
}

};

相关文章

网友评论

      本文标题:Insert Node in a Binary Search T

      本文链接:https://www.haomeiwen.com/subject/vgggettx.html