在二叉查找树中插入节点

来源:互联网 发布:英氏童装加盟 知乎 编辑:程序博客网 时间: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;}    }};
感想:感觉本题主要考察了什么是二叉查找树,根据定义再插入节点。

原创粉丝点击