在二叉查找树中插入节点
来源:互联网 发布:蚌埠市农村金融数据 编辑:程序博客网 时间:2024/06/07 14:24
给定一棵二叉查找树和一个新的树节点,将节点插入到树中。
你需要保证该树仍然是一棵二叉查找树。
样例
给出如下一棵二叉查找树,在插入节点6之后这棵二叉查找树可以是这样的:
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)
{
root=new TreeNode(node->val);
return root;
}
else if(node->val<root->val)
{
root->left=insertNode(root->left,node);
return root;
}
else
root->right=insertNode(root->right,node);
return root;
}
};
做题感想:审完题目,心想就是二叉排序树的插入问题嘛,然后就把课本上的代码打上了,但是没注意到函数的返回类型。
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 浏览器内核渲染引擎渲染原理
- java出现Resource leak: 'input' is never closed 问题
- css选择器以及基础介绍
- Dubbo标签解析
- Java模块 -- Apache Commons Pool 对象池_简介
- 在二叉查找树中插入节点
- 【php基础班】第16天 网络概述、PHP工作原理、Apache语法检查、Apache配置、虚拟主机
- Remove Nth Node From End of List
- spring 的以来注入的基本注入(IOC)的beans配置。
- StringBuilder类的Capacity属性和Length属性
- 二叉搜索树
- 英语背记5
- AtCoder Regular Contest 074 F Lotus Leaves
- [SDOI2008]仪仗队(phi)