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

    原题网址:http://www.lintcode.com/zh-cn/problem/insert-node-in-a-binary-search-tree/

    给定一棵二叉查找树和一个新的树节点,将节点插入到树中。

    你需要保证该树仍然是一棵二叉查找树。

     注意事项

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

    样例

    给出如下一棵二叉查找树,在插入节点6之后这棵二叉查找树可以是这样的:

      2             2
     /            / 
    1   4   -->   1   4
       /             /  
      3             3   6
    
    挑战 

    能否不使用递归?

     1 #include <iostream>
     2 #include <vector>
     3 #include <math.h>
     4 #include <string>
     5 #include <algorithm>
     6 using namespace std;
     7 
     8 class TreeNode 
     9 {
    10 public:
    11     int val;
    12     TreeNode *left, *right;
    13     TreeNode(int val)
    14     {
    15         this->val = val;
    16         this->left = this->right = NULL;
    17     }
    18 
    19 
    20     TreeNode * insertNode(TreeNode * root, TreeNode * node) //插入位置需要进行判断;
    21     {
    22         int nodeValue=node->val;
    23         TreeNode *p=new TreeNode(nodeValue);
    24 
    25         if (root==NULL)
    26         {
    27             root=p;
    28             return root;
    29         }
    30         TreeNode *tempp=root;
    31         while(tempp!=NULL)   //注意循环终止条件,无论怎么判断tempp都不可能为NULL,所以要用return语句结束函数的执行;
    32         {
    33             if (nodeValue<tempp->val)
    34             {
    35                 if (tempp->left==NULL)
    36                 {
    37                     tempp->left=p;
    38                     return root;
    39                 }
    40                 else
    41                 {
    42                     tempp=tempp->left;
    43                 }
    44             }
    45             else
    46             {
    47                 if (tempp->right==NULL)
    48                 {
    49                     tempp->right=p;
    50                     return root;
    51                 }
    52                 else
    53                 {
    54                     tempp=tempp->right;
    55                 }
    56             }
    57         }
    58         
    59     }
    60 
    61     TreeNode * insertnode(TreeNode * root, TreeNode * node);
    62 };
    63 
    64 TreeNode* TreeNode::insertnode(TreeNode * root, TreeNode * node) //使用递归; 65 { 66 if (root==NULL) 67 { 68 root=node; 69 return root; 70 } 71 if (node->val<root->val) 72 { 73 root->left=insertnode(root->left,node); 74 } 75 else 76 { 77 root->right=insertnode(root->right,node); 78 } 79 return root; 80 }

    参考:

    https://www.cnblogs.com/xiaobingqianrui/p/6533556.html

    https://www.cnblogs.com/cc11001100/p/6243518.html

  • 相关阅读:
    Java LinkedList 源码剖析
    Java并发编程:线程池的使用
    Java 线程池的原理与实现
    多线程JAVA篇(一)
    软件开发中会用到的图
    linux文件名匹配——通配符使用
    XModem协议
    dmesg 命令七种用法
    定位精度单位CEP、RMS、2DRMS常识
    5G NR 技术简介
  • 原文地址:https://www.cnblogs.com/Tang-tangt/p/8633371.html
Copyright © 2011-2022 走看看