一、原题目
Given a binary tree, return the inorder traversal of its nodes' values
二、题目大意
给定一个棵树,返回中序遍历。
三、作者代码:
作者一:
#思路一:递归算法
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
res=[]
self.centertrave(root,res)
return res
def centertrave(self,root,res):
if root:
self.centertrave(root.left,res)
res.append(root.val)#中序遍历,添加值的地方在根结点
self.centertrave(root.right,res)
#思路二:迭代方法
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
stack,res=[],[]
while True:
while root:#遍历到左子树的叶子结点
stack.append(root)
root=root.left
if not stack:#没有元素,返回res,遍历完成
return res
node=stack.pop()#到达叶子结点,也是根结点
res.append(node.val)
root=node.right#到右子树
return res
作者原文链接:https://leetcode.com/problems/binary-tree-inorder-traversal/discuss/31381/Python-recursive-and-iterative-solutions.
作者二:
class Solution:
# @param {TreeNode} root
# @return {integer[]}
def inorderTraversal(self, root):
result, stack = [], [(root, False)]
while stack:
cur, visited = stack.pop()
if cur:
if visited:
result.append(cur.val)
else:
stack.append((cur.right, False))
stack.append((cur, True))
stack.append((cur.left, False))
return result
作者三:
class Solution(object):
def inorderTraversal(self, root):
res, stack = [], []
while stack or root:
if root:
stack.append(root)
root = root.left#一直遍历到左子树的根结点
else:
node = stack.pop()#元素不存在,已经放过结点了
res.append(node.val)
root = node.right#遍历右子树
return res
作者原文链接:https://leetcode.com/problems/binary-tree-inorder-traversal/discuss/158278/Python-Stack-or-DFS-tm
四、知识点:
作者三:遍历完左子树,弹出元素,向结果集中添加值,遍历右子树(写这个是因为本人写的时候,也是这个思路,但是没有实现,在遍历完左子树,不知道怎么操作了,思路不清楚)
五、来源
题目连接:https://leetcode.com/problems/binary-tree-inorder-traversal/
座右铭:站在别人的思想上,看见自己的不足,传播错误的经验,愿君不重蹈覆辙。
由于受限于本人经验,难免不足,如有建议,欢迎留言交流。
说明:本人对作者的内容进行了简单排版和总结,想看原版,上面有链接,如果喜欢,请点赞,您的鼓励是本人前进的最好动力。本人的这个分类,就是为了汇聚不同思路,为大家学习提供方便,同时为了以后能够全面的理解这里的代码。(现在有些理解不全面,请见谅)
---------------------
作者:路漫漫,远修兮
来源:CSDN
原文:https://blog.csdn.net/qq_41827968/article/details/88756403
版权声明:本文为博主原创文章,转载请附上博文链接!