您的位置:首页 > 其它

在二叉查找树中插入节点

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;}
}
};感想:感觉本题主要考察了什么是二叉查找树,根据定义再插入节点。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: