码迷,mamicode.com
首页 > 其他好文 > 详细

[容易]在二叉查找树中插入节点

时间:2016-07-01 01:09:50      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:

题目来源:http://www.lintcode.com/zh-cn/problem/insert-node-in-a-binary-search-tree/

技术分享

C++版 VS2012测试通过:

 1 //#include <iostream>
 2 //#include <vector>
 3 //#include <queue>
 4 //#include <algorithm>
 5 //using namespace std;
 6 //
 7 //class TreeNode {
 8 //public:
 9 //    int val;
10 //    TreeNode *left, *right;
11 //    TreeNode(int val=-1) {
12 //    this->val = val;
13 //    this->left = this->right = NULL;
14 //  }
15 //};
16 
17 //以前序遍历创建二叉树
18 //输入21##43###
19 //void CreateBiTree(TreeNode **T)//*T是指向BiTNode的指针
20 //{
21 //    *T=new TreeNode;
22 //    if(*T==NULL)//如果*T还是指向NULL,表示内存分配失败,退出程序
23 //        exit(OVERFLOW);
24 //    char ch;
25 //    cin>>ch;
26 //    if(ch==‘#‘)
27 //        *T=NULL;
28 //    else
29 //    {
30 //        (*T)->val=ch-‘0‘;//*T指向的节点的data分配内容,即生成根节点
31 //        CreateBiTree(&((*T)->left));//创建&(*T)->lchild临时变量,传入CreateBiTree,构造左子树
32 //        CreateBiTree(&((*T)->right));//创建&(*T)->rchild临时变量,传入CreateBiTree,构造右子树
33 //    }
34 //}
35 
36 class Solution {
37 public:
38     /**
39      * @param root: The root of the binary search tree.
40      * @param node: insert this node into the binary search tree
41      * @return: The root of the new binary search tree.
42      */
43     TreeNode* insertNode(TreeNode* root, TreeNode* node) {
44         // write your code here
45       if (root == NULL) {
46       return node;
47         }
48         if (node->val < root->val) {
49             root->left = insertNode(root->left, node);
50             return root;
51         }
52         root->right = insertNode(root->right, node);
53         return root;
54     }
55 };
56 
57 //测试
58 //int main()
59 //{
60 //    Solution s;
61 //    TreeNode **pp;//定义指向BiTNode的二级指针pp
62 //    TreeNode *p;//定义指向BiTNode的指针p
63 //    pp=&p;//pp指向p
64 //    p=NULL;//初始化p指向NULL
65 //    CreateBiTree(pp);//传入指向p的地址,创建二叉树
66 
67 //    TreeNode *n=new TreeNode;//定义指向BiTNode的指针n作为插入的节点
68 //    n->val=6;
69 //    TreeNode *r;  
70 //    r=s.insertNode(*pp,n);//插入结点n
71 
72 //    //检查插入是否正确,这里的测试方法有点傻...
73 //    cout<<r->val;//输出根节点值
74 //    cout<<endl;
75 //    cout<<r->left->val;//输出左子数值
76 //    cout<<endl;
77 //    cout<<r->right->val<<" "<<r->right->left->val<<" "<<r->right->right->val;//输出右子数值
78 //    cout<<endl;
79 //}

Python2.7版 spider测试通过:

[容易]在二叉查找树中插入节点

标签:

原文地址:http://www.cnblogs.com/hslzju/p/5631572.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!