在二叉查找树中插入节点
来源:互联网 发布:英氏童装加盟 知乎 编辑:程序博客网 时间:2024/06/05 08:47
问题描述:给定一棵二叉查找树和一个新的树节点,将节点插入到树中。
你需要保证该树仍然是一棵二叉查找树。
思路:有题目可知,利用递归的思想。先判断二叉树是否为空,若空直接将节点赋值给根节点并返回;
否则判断插入节点与根节点值的大小,若小于根节点,判断左节点是否为空,若空,赋节点值,若非空,递归调用原函数,
若大于根节点的值,判断右孩子是否为空,再调用原函数。
代码:
/** * 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; if(root->val>node->val) {root->left=insertNode(root->left,node); return root; } if(root->val<node->val) {root->right=insertNode(root->right,node); return root;} }};感想:感觉本题主要考察了什么是二叉查找树,根据定义再插入节点。
阅读全文
0 0
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 微软请你学Linux第三季: 6月最后的约会,再次诚意邀请!
- linux C语言开发 笔记
- lintcode——在二叉查找树中插入节点
- 医院客户关系管理——不仅仅是一种管理新模式
- Linux 驱动模块及模块之前的通信(模块函数的相互调用)
- 在二叉查找树中插入节点
- kaggle案例:广告点击率预估+LR
- IOS 横屏状态栏不显示的问题
- android 万能倒计时
- cf Educational Codeforces Round 20 F. Coprime Subsequences
- 如何解决虚拟机克隆后ip冲突问题
- android_防止被反编译 混淆
- 如何设计数据库
- 无线调试