zoukankan      html  css  js  c++  java
  • 在二叉树中插入节点

    Given a binary search tree and a new tree node, insert the node into the tree. You should keep the tree still be a valid binary search tree.

     Notice

    You can assume there is no duplicate values in this tree + node.

    Example

    Given binary search tree as follow, after Insert node 6, the tree should be:

      2             2
     /            / 
    1   4   -->   1   4
       /             /  
      3             3   6
    /**
     * 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 == NULL)return root;
            
            TreeNode *p = root;
            while(p != NULL)
            {
                if(p->val == node->val)return root;
                else if(p->val < node->val)
              {
                if(p->right == NULL)
                {
                    p->right = node;
                    return root;
                }
                else p = p->right;
                    
              }
              else if(p->val > node->val)
              {
                if(p->left == NULL)
                {
                    p->left = node;
                    return root;
                }
                else p = p->left;
              }
            }
            
        }
    };
  • 相关阅读:
    洛谷 P2053 :[SCOI2007]修车(拆点+最小费用流)
    LightOJ
    spark简单入门
    crontab 应用
    HttpClient的使用
    build.sbt的定义格式
    Scalatra
    SBT 构建scala eclipse开发
    mysql 存在更新,不存在插入
    Flash Vector例子
  • 原文地址:https://www.cnblogs.com/dynas/p/6993981.html
Copyright © 2011-2022 走看看