Day24-Construct Binary Search Tree from Preorder Traversal(Medium)
问题描述:
Return the root node of a binary search tree that matches the given preorder traversal.
(Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val. Also recall that a preorder traversal displays the value of the node first, then traverses node.left, then traverses node.right.)
It’s guaranteed that for the given test cases there is always possible to find a binary search tree with the given requirements.
依据前序遍历构造二叉搜索树
解法:
这道题好像四月挑战的时候就做过了。。。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
if len(preorder) == 0:
return None
#因为先序遍历所以第一个元素一定为跟节点。
root = TreeNode(preorder[0])
#先序遍历先访问根节点然后左子树,然后右子树,同时左子树的节点一定比根节点的数小,右子树的节点一定比根节点的数大。所以向后寻找第一个比根节点大的数字就是右子树的根节点。然后递归求解左右子树即可
i = 1
while i < len(preorder):
if preorder[i] > root.val:
break
i += 1
root.left = self.bstFromPreorder(preorder[1:i])
root.right = self.bstFromPreorder(preorder[i:])
return root
解法二:
虽然上个月刚做过,但是今天不写道算法题就过去,实在不太舒服啊(受虐狂。。)于是上discuss中找了另一种解法,同时感叹leetcode真是能人辈出,各种新奇的解法都有,这里贴上一个我认为还是很大众的解法出来。
就是不用递归而用栈,我们用栈存储左子树上的节点,遇到右子树上的点时,我们就从栈中往外推值,直到找到右子树的根节点为止。然后将右子树再送入栈中循环。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
if len(preorder) == 0:
return None
##换一种写法,不使用递归求解而是用栈。
root = TreeNode(preorder[0])
help_stack = [root]
for val in preorder[1:]:
if help_stack[-1].val > val:
help_stack[-1].left = TreeNode(val)
help_stack.append(help_stack[-1].left)
else:
while help_stack and help_stack[-1].val < val:
temp = help_stack.pop()
temp.right = TreeNode(val)
help_stack.append(temp.right)
return root
247

被折叠的 条评论
为什么被折叠?



