在二叉查找树中插入节点

来源:互联网 发布: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;
    }

  };

感想:

利用递归,根据节点值进行比较找到合适的位置