在二叉查找树中插入节点
来源:互联网 发布:php匹配字符串 编辑:程序博客网 时间:2024/06/05 06:44
问题描述:
给定一颗二叉查找树和一个新的树节点,将节点插入到树中。你需要保证该树仍是一颗二叉查找树。
实现思路:
利用递归,如果该节点的值大于根节点的值插入右子树,否则插入左子树。
代码:
/**
* 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)
return node;
else if(node->val>root->val) root->right=insertNode(root->right,node);
else root->left=insertNode(root->left,node);
return root;
}
};
感想:
利用递归,根据节点值进行比较找到合适的位置
阅读全文
0 0
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- android代码规范
- error: no such device: xxx xxx Entering rescue mode... grub rescue >
- 非递归中序遍历二叉树
- Android开发笔记 合理解决获取唯一标识符及其授权问题
- WebSocket基本应用
- 在二叉查找树中插入节点
- Matlab中关于CMA的介绍
- 关于oracle创建定时器和定时器创建成功后不运行的问题解决
- LNMP
- 机器学习算法一览
- Thread物联网标准
- Vim操作的四种模式与切换
- 项目源码总结
- 最短路径