在二叉查找树中插入节点
2017-05-18 16:56
183 查看
问题描述:给定一棵二叉查找树和一个新的树节点,将节点插入到树中。
你需要保证该树仍然是一棵二叉查找树。
思路:有题目可知,利用递归的思想。先判断二叉树是否为空,若空直接将节点赋值给根节点并返回;
否则判断插入节点与根节点值的大小,若小于根节点,判断左节点是否为空,若空,赋节点值,若非空,递归调用原函数,
若大于根节点的值,判断右孩子是否为空,再调用原函数。
代码:/**
* 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;}
}
};感想:感觉本题主要考察了什么是二叉查找树,根据定义再插入节点。
你需要保证该树仍然是一棵二叉查找树。
思路:有题目可知,利用递归的思想。先判断二叉树是否为空,若空直接将节点赋值给根节点并返回;
否则判断插入节点与根节点值的大小,若小于根节点,判断左节点是否为空,若空,赋节点值,若非空,递归调用原函数,
若大于根节点的值,判断右孩子是否为空,再调用原函数。
代码:/**
* 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;}
}
};感想:感觉本题主要考察了什么是二叉查找树,根据定义再插入节点。
相关文章推荐
- LintCode(85)在二叉查找树中插入节点
- 在二叉查找树中插入节点
- C++模板实现二叉查找树(一 树的数据结构定义与节点插入)
- 85.在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 算法-二叉查找树-插入节点
- C++模板实现二叉查找树(一 树的数据结构定义与节点插入)
- 在二叉查找树中插入节点
- 算法-二叉查找树-插入节点
- C++模板实现二叉查找树(一 树的数据结构定义与节点插入)
- LintCode 85. 在二叉查找树中插入节点
- [javaSE] 数据结构(二叉查找树-插入节点)
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- C++模板实现二叉查找树(一 树的数据结构定义与节点插入)
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 再二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点