99恢復二叉樹

月為暮發表於2020-08-08
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# 如果第一個節點沒有找到,第一個就等於前一個節點大於root節點的前一個節點
# 如果第一個節點已經找到,第二個就等於前一個節點大於root節點的root節點
class Solution:
def recoverTree(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
self.firstNode = None
self.secondNode = None
self.preNode = TreeNode(float("-inf"))
self.dfs(root)
self.firstNode.val,self.secondNode.val = self.secondNode.val,self.firstNode.val
def dfs(self,root):
if not root:
return
self.dfs(root.left)
if self.firstNode == None and self.preNode.val > root.val:
self.firstNode = self.preNode
if self.firstNode and self.preNode.val > root.val:
self.secondNode = root
self.preNode = root
self.dfs(root.right)












相關文章