1. 程式人生 > >85 在二叉查找樹中插入節點

85 在二叉查找樹中插入節點

tor logs .html ane == .cn gpo blog color

原題網址: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.

您在真實的面試中是否遇到過這個題? Yes 樣例

給出如下一棵二叉查找樹,在插入節點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 }

參考:

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

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

85 在二叉查找樹中插入節點