摘要:栈的意义价值具有时间性,先进后出。比如递归的后序遍历,先序遍历,二叉树的按层次打印。根据需求不同,在中暂时储存的元素单元也不同,元素的先后顺序也不同。应用对顺序有要求的数据。
stack 栈的意义价值: 具有时间性,先进后出。 所以具有时间关联顺序的元素可以通过这个时间。 比如递归的后序遍历,先序遍历,
二叉树的按层次打印。 根据需求不同,在stack中暂时储存的元素单元也不同,元素的先后顺序也不同。
应用:对顺序有要求的数据。二叉树的处理。
Given a binary tree, return the postorder traversal of its nodes" values.
Example:
Input: [1,null,2,3]
1
2 /
3
Output: [3,2,1]
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
stack=list()
ans=list()
stack.append(root)
while stack:
node_cur=stack.pop()
if node_cur.val:
ans.append(node_cur.val)
if node_cur.left:
stack.append(node_cur.left)
if node_cur.right:
stack.append(node_cur.right)
return ans[::-1]
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/42237.html
摘要:按顺序放入,正好方面是从到,顺序方面是从最右到最左,因为是先入后出。这样最后一下就是先左后右,先子后根。 590. N-ary Tree Postorder Traversal Problem Given an n-ary tree, return the postorder traversal of its nodes values.For example, given a 3-ar...
摘要:题目解答最主要的思想是先存的话,整个存储的顺序会变反,所以要插入存储进去。 题目:Given a binary tree, return the postorder traversal of its nodes values. For example:Given binary tree {1,#,2,3}, 1 2 / 3return [3,2,1]. 解答:最主要的思想是先存...
摘要:思路在的顺序里,先,然后再左右。所以根据可以知道的。接着再分别在和的里面重复找以及左右的过程。首先的包括和,以及对应的起始和结束位置,对应的起始和结束位置。返回值为,因为每个里要一个,同时找到它的和,左右节点通过返回值获得。同时的不需要了。 From Preorder and Inorder 思路在preorder的顺序里,先root,然后再左右。所以根据preorder可以知道roo...
摘要:题目链接题目分析后序遍历,这题也是比较基础的题目了。思路先遍历子节点,再遍历根节点。最终代码若觉得本文章对你有用,欢迎用爱发电资助。 D44 590. N-ary Tree Postorder Traversal 题目链接 590. N-ary Tree Postorder Traversal 题目分析 后序遍历,这题也是比较基础的题目了。 思路 先遍历子节点,再遍历根节点。 最终代码...
阅读 2542·2023-04-25 15:50
阅读 1506·2021-09-22 15:49
阅读 3496·2021-09-22 15:06
阅读 4017·2019-08-30 15:54
阅读 2659·2019-08-29 11:33
阅读 2361·2019-08-23 17:56
阅读 2680·2019-08-23 17:06
阅读 1479·2019-08-23 15:55