LeetCode-algorithms 145. Binary Tree Postorder Traversal
来源:互联网 发布:淘宝店怎么运营 编辑:程序博客网 时间:2024/05/22 04:57
题目:
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [3,2,1]
.
Note: Recursive solution is trivial, could you do it iteratively?
思考:
这题考的是树的遍历。首先树的先序、后序、中序遍历是都可以使用递归的方法去直接求解,但是这里题目要求不要使用递归,因此我们也可以借助递归的思想去使用栈,把需要遍历的结点依次放入栈中,以遍历整一棵树。
这里有两点需要注意的。一个是放入栈中的类型,一类是节点类型,是可以往下继续分支的;另一类是数值类型,是指该节点的值。每次遇到一个节点的时候,我们就会放入该节点的左右儿子,以及该节点的值,用0表示节点,用1表示数值,这样可以方便我们之后分辨类型。第二点是放入左右儿子以及节点值的顺序,不同的顺序则代表了各种的遍历-先序:右儿子,左儿子,值;中序:右儿子,值,左儿子;后序:值,右儿子,左儿子;对于本题来说,我们选择最后一种。
代码:
# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = Nonedef myAppend(root,stack): stack.append([root.val,1]) stack.append([root.right,0]) stack.append([root.left,0]) class Solution(object): def postorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ list = [] stack = [] if root is not None: myAppend(root,stack) while len(stack)!=0: node = stack.pop() if node[1] == 1: list.append(node[0]) elif node[0] is not None: myAppend(node[0],stack) return list
结果:
0 0
- LeetCode-algorithms 145. Binary Tree Postorder Traversal
- Algorithms—145.Binary Tree Postorder Traversal
- [LeetCode]145.Binary Tree Postorder Traversal
- [leetcode] 145.Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal LeetCode
- Leetcode 145. Binary Tree Postorder Traversal
- [LeetCode]145. Binary Tree Postorder Traversal
- Leetcode 145. Binary Tree Postorder Traversal
- leetcode 145. Binary Tree Postorder Traversal
- LeetCode 145. Binary Tree Postorder Traversal
- LeetCode-145.Binary Tree Postorder Traversal
- [leetcode] 145. Binary Tree Postorder Traversal
- LeetCode 145. Binary Tree Postorder Traversal
- leetcode 145. Binary Tree Postorder Traversal
- [LeetCode]problem 145. Binary Tree Postorder Traversal
- Leetcode 145. Binary Tree Postorder Traversal
- [LeetCode] 145. Binary Tree Postorder Traversal
- LeetCode 145. Binary Tree Postorder Traversal
- 缅甸新葡京真的经不起等待
- iOS——视频点播、视频直播、飞心点赞、弹幕
- python爬虫爬取内容中,\xa0,\u3000的含义
- void f(n,s)
- 可重入函数与线性安全的区别与关系
- LeetCode-algorithms 145. Binary Tree Postorder Traversal
- 原生JS中的Ajax操作
- Android6.0M运行时权限封装
- mysql 部分语法总结
- LSTM 递归神经网络 基本结构 及 TensorFlow 示例模型介绍
- 编码练习——Java-String-API-练习
- Webpack学习笔记(二)
- Swageer学习文档
- SpringMVC错误②