难度指数:⭐⭐⭐⭐⭐
知识点:
算法参考:
2023华为OD机试真题B卷【二维伞的雨滴效应】Python 实现
import functools
import collections
import math
from itertools import combinations
from re import match
import copy
from collections import defaultdict
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
pre_order = [int(x) for x in input().split(" ")]
root = TreeNode(pre_order[0])
# 用一个栈来保存节点
stack = []
stack.append(root)
# 辅助节点, 用来判断是否是二叉搜索树
helper = TreeNode(-1)
flag = True
# 判断并构造二叉搜索树
for i in range(1, len(pre_order)):
node = stack[-1]
currentNode = TreeNode(pre_order[i])
while (len(stack)>0 and stack[-1].val < currentNode.val) :
node = stack[-1]
stack.pop()
if(len(stack)>0):
helper = stack[-1]
#不满足二叉搜索树属性直接跳出
if (node.val < currentNode.val) :
node.right = currentNode
helper = node
else:
if(currentNode.val < helper.val):
flag = False
break
node.left = currentNode
stack.append(currentNode)
if(flag):
leftNode = root
while (leftNode.left is not None or leftNode.right is not None):
if(leftNode.left is not None):
leftNode = leftNode.left
else :
leftNode = leftNode.right
rightNode = root
while (rightNode.left is not None or rightNode.right is not None):
if(rightNode.right is not None):
rightNode = rightNode.right
else :
rightNode = rightNode.left
res = "1"
if leftNode.val == root.val:
res += " 0"
else:
res += " " + str(leftNode.val)
if rightNode.val == root.val:
res += " 0"
else:
res += " " + str(rightNode.val)
print(res)
else :
print("0 0 0")
Mine:
idea
代码实现
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def buildTree(flag):
stack=[root]
l_node = TreeNode(-1)
for i in range(1, len(preorder)):
node = stack[-1]
current_node = TreeNode(preorder[i])
while len(stack) > 0 and stack[-1].val < current_node.val:
node = stack[-1]
stack.pop()
if len(stack) > 0:
l_node = stack[-1]
if node.val < current_node.val:
node.right = current_node.val
l_node = node
else:
if current_node.val < l_node.val:
flag = False
break
node.left = current_node.val
stack.append(current_node)
return flag
def raindrop():
res[0] = 1
node = root
while node.left is not None or node.right is not None:
if node.left is not None:
node = TreeNode(node.left)
else:
node = TreeNode(node.right)
res[1] = node.val
res[2] = preorder[-1]
return res
preorder = [int(i) for i in input().split(' ')]
root = TreeNode(preorder[0])
flag = True
res = [0,0,0]
flag = buildTree(flag)
if flag:
res = raindrop()
print(' '.join(map(str, res)))