二叉搜索树中的插入操作 python

作者: 18届cyl

时间:2020-10-1

标签:二叉搜索树 中等 leetcode

题目描述

给定二叉搜索树(BST)的根节点和要插入树中的值,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 输入数据保证,新值和原始二叉搜索树中的任意节点值都不同。

注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回任意有效的结果。

示例

例如,

给定二叉搜索树:

    4
   / \
  2   7
 / \
1   3

和 插入的值: 5
你可以返回这个二叉搜索树:

     4
   /   \
  2     7
 / \   /
1   3 5

或者这个树也是有效的:

     5
   /   \
  2     7
 / \   
1   3
     \
      4

提示:

给定的树上的节点数介于 0 和 10^4 之间
每个节点都有一个唯一整数值,取值范围从 0 到 10^8
-10^8 <= val <= 10^8
新值和原始二叉搜索树中的任意节点值都不同

题解思路

1、若树为空则直接建立一个根节点
2、由于树中每一个值肯定不一样,想要插入就二插搜索一遍树找到最底部node
3、若给定val > node.val 则插到右子树 否则插入到左子树

代码

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def insertIntoBST(self, root, val):
        """
        :type root: TreeNode
        :type val: int
        :rtype: TreeNode
        """
        if root is None:
            root = TreeNode(val,None,None)
        else:
            node = root
            while(not node is None):
                if node.val > val:
                    if not node.left is None:
                        node = node.left
                    elif node.left is None:
                        node.left = TreeNode(val,None,None)
                        break
                elif node.val < val:
                    if not node.right is None:
                        node = node.right
                    elif node.right is None:
                        node.right = TreeNode(val,None,None)
                        break
        
        return root

猜你喜欢

转载自blog.csdn.net/cyl_csdn_1/article/details/108893796