首页 > 其他 > 详细

【树】701. 二叉搜索树中的插入操作

时间:2020-05-03 16:26:59      阅读:59      评论:0      收藏:0      [点我收藏+]

题目:

技术分享图片

 

 

解答:

概述:

二叉搜索树的巨大优势是:在平均情况下,能够在log(N)的时间内完成搜索和插入元素。

二叉搜索树的插入方法非常简单,我们将插入的节点作为叶子节点的子节点插入。插入到哪个节点可以遵循以下原则:

(1)若 val > node->val, 插入到右子树;

(2)若val < node->val,插入到左子树;

 

方法一:递归

算法:

(1)若roo == NULL, 则返回TreeNode(val);

(2)若val > root->val,插入到右子树;

(3)若val < root->val,插入到左子树;

(4)返回root;

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     TreeNode* insertIntoBST(TreeNode* root, int val) 
13     {
14         if (root == NULL) 
15         {
16             return new TreeNode(val);
17         }
18 
19         // insert into the right subtree
20         if (val > root->val) 
21         {
22             root->right = insertIntoBST(root->right, val);
23         }
24         // insert into the left subtree
25         else
26         {
27             root->left = insertIntoBST(root->left, val);
28         }
29         return root;
30 
31     }
32 };

 

【树】701. 二叉搜索树中的插入操作

原文:https://www.cnblogs.com/ocpc/p/12822031.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!