701. (leetcode)Insert into a Binary Search Tree

题目

在这里插入图片描述

解题思路

简单来说,就是一直往下找,如果val的值小,那么往左线找,如果val的值大于结点的值,那么往右线找,直到找到了一个为null的结点,把它的父节点添加一个值为val的结点即可。

我的代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
        def DFSinsert(T,father,dis): 
            nonlocal val
            if T:
                if val<=T.val:
                    DFSinsert(T.left,T,1)
                else:
                    DFSinsert(T.right,T,2)
            elif dis==1:
                father.left=TreeNode(val)
            elif dis==2:
                father.right=TreeNode(val)
            else:
                T=TreeNode(val)
            return T
        return DFSinsert(root,None,0) 

高效代码

简明易解。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def insertIntoBST(self, root: 'TreeNode', val: 'int') -> 'TreeNode':
        if not root:
            return TreeNode(val)
        if root.val>val:
            root.left=self.insertIntoBST(root.left,val)
        else:
            root.right=self.insertIntoBST(root.right,val)
        return root

猜你喜欢

转载自blog.csdn.net/xiabenshu/article/details/89262192
今日推荐