程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Force deduction binary tree middle order traversal (non recursive) Python

編輯:Python
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right

The test system has defined the nodes , Node value is int type , without L/R, Its value is None Not the example null

My general idea flow is :

  1. (while) All the way into the left subtree ( At the same time, its parent node is put on the stack ), Until you see the left leaf node and record result until
  2. Put the current node's val Record in result
  3. (while) All the way out of the stack there is no right child node , Record while taking val
  4. When the node has a right child , If it is a leaf node, record it in result, Not just as an access point for the next loop
stack = []
result = []
visit = root
while visit:
while visit.left:
# When there is a left child
if isinstance(visit.left, int):
# Left the child -> leaf
result.append(visit.left)
# Access the left node
else:
# Left the child -> subtree
stack.append(visit)
visit = visit.left
# Stack current node , Visit left child
result.append(visit.val)
# Access root
while stack and not visit.right:
# Stack is not empty. 、 The visited node has no right child
visit = stack.pop()
result.append(visit.val)
if isinstance(visit.right, int):
# The right child -> leaf
result.append(visit.right)
else:
# The right child -> subtree
visit = visit.right
return result

The test of the buckle is not accurate , Many tests fluctuate a little


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved