LintCode 85 [Insert Node in a Binary Search Tree]

原题

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

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

  2             2
 / \           / \
1   4   -->   1   4
   /             / \ 
  3             3   6

解题思路

  • 如果root为空,给root赋值
  • root不为空,根据root.val与node.val的大小去判断往左儿子走还是右儿子走

完整代码

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""
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:
            if root.left:
                self.insertNode(root.left, node)
            else:
                root.left = node
        else:
            if root.right:
                self.insertNode(root.right, node)
            else:
                root.right = node
        return root
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 树的概述 树是一种非常常用的数据结构,树与前面介绍的线性表,栈,队列等线性结构不同,树是一种非线性结构 1.树的定...
    Jack921阅读 9,942评论 1 31
  • 参考两篇其他bolg总结的二叉树:https://github.com/xy7313/lintcode/blob/...
    暗黑破坏球嘿哈阅读 7,044评论 0 1
  • 树 树 树是一种重要的数据结构,通过链表建立一棵树: 用链表的结构构建树,就是使树的每一条分支都建立一个链表来存储...
    JnJnLee阅读 1,605评论 0 0
  • 红黑树是平衡二叉查找树的一种。为了深入理解红黑树,我们需要从二叉查找树开始讲起。 BST 二叉查找树(Binary...
    kanehe阅读 5,188评论 0 8
  • 昨晚好闺蜜发了我们去年的合照,看着合照不禁想起大学的一幕幕,至今记忆尤新的是有一段时间,我谈恋爱了,分了,但都忍住...
    温一壶茶伴月光到老阅读 1,449评论 1 3