在二叉查找树中插入节点

题目描述:给定一棵二叉查找树和一个新的树节点,将节点插入到树中。你需要保证该树仍然是一棵二叉查找树。

样例:给出如下一棵二叉查找树,在插入节点6之后这棵二叉查找树可以是这样的:

《在二叉查找树中插入节点》


关键在于对二叉查找树的认识。二叉查找树是说一颗二叉树的左子树中所有节点的值均小于根节点的值,而右子树中所有节点的值均大于根节点。

所以,我们可以用递归的算法解决这个问题:

1. 若根节点的值大于要插入节点的值,则这个要插入的节点一定在根节点的左子树中,我们就用这个插入节点的函数处理左子树

2. 若根节点的值小于要插入节点的值,则这个要插入的节点一定在根节点的右子树中,我们就用这个插入节点的函数处理右子树

3. 若根节点为空,则将根节点赋值为这个要插入的节点(这也是递归“触底”的条件)

可以写出代码:

class Solution:
    """
    @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.
    """
    def insertNode(self, root, node):
        if root is None:
            root = node
        elif root.val > node.val:
            root.left = self.insertNode(root.left, node)
        elif root.val < node.val:
            root.right = self.insertNode(root.right, node)
        return root
        # write your code here

    原文作者:二叉查找树
    原文地址: https://blog.csdn.net/guoziqing506/article/details/51605651
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞