"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
# @param {TreeNode} root the root of the binary tree
# @return {List[str]} all root-to-leaf paths
def binaryTreePaths(self, root):
# Write your code here
# Write your code here
if root is None:
return []
stack = [root]#將root節(jié)點放入棧里面
result = []
while len(stack) != 0:#棧不為空就循環(huán)操作
topnode = stack[-1] #讀取棧頂元素逼友,但是將元素彈出
#從棧頂節(jié)點開始遍歷子節(jié)點杨幼。直到尋找到葉子節(jié)點位置
while topnode.left is not None or topnode.right is not None:
if topnode.left is not None:#尋找過程中優(yōu)先尋找位于左子樹的節(jié)點
stack.append(topnode.left)
p = topnode.left
topnode.left = None #入棧后要置空宾袜,否則出棧的條件無法判斷,或者可以尋找其他的辦法標(biāo)記哪些節(jié)點已經(jīng)入過棧猜拾。
topnode = p
elif topnode.right is not None:
stack.append(topnode.right)
p = topnode.right
topnode.right = None
topnode = p
path = ""
#到這里表示已經(jīng)尋找完一條路徑信不,拼接字符串
for idx,node in enumerate(stack):
path += str(node.val)
if idx != len(stack)-1:
path += "->"
result.append(path)
#將最后一個節(jié)點出棧麻昼。一直尋找到?jīng)]有入棧的節(jié)點宵统。
while topnode.left is None and topnode.right is None:
stack.pop()
if len(stack) == 0:
return result
topnode = stack[-1]
return result