0145-leetcode算法实现之二叉树的后续遍历-binary-tree-postorder-traversal-python&golang实现
给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [3,2,1]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-postorder-traversal
python
# 0145.二叉树后序遍历
# 递归 & 迭代
class Solution:
def postOrderRecur(self, head: TreeNode) -> [int]:
"""
递归, 左右根,LRN
:param head:
:return:
"""
def traversal(head):
if head == None:
return
traversal(head.left)
traversal(head.right)
print(head.val + " ")
res.append(head.val)
res = []
traversal(head)
return res
def postOrderItration(self, head: TreeNode):
"""
迭代, 左右根, LRN
stack入栈顺序: N L R 中左右
res添加顺序:N R L 中右左, 反转后:左右中
:param head:
:return:
"""
if head == None:
return
stack = [head]
res = []
while stack:
node = stack.pop()
# 先处理中节点
res.append(node.val)
# 左孩子先入栈
if node.left:
stack.append(node.left)
# 右孩子后入栈
if node.right:
stack.append(node.right)
# 返回前将res反转
return res[::-1]
goalng
package main
import "container/list"
// 二叉树的后序遍历 -> 递归 && 迭代
// 递归遍历
func PostOrderTraversal(root *TreeNode) []int {
// 递归遍历, LRN, 左右根
var res = []int{}
var postorder func(node *TreeNode)
postorder = func(node *TreeNode) {
if node == nil {
return
}
postorder(node.Left)
postorder(node.Right)
res = append(res, node.Val)
}
postorder(root)
return res
}
// 迭代遍历 LRN 左右中
// 压栈顺序:中右左(前序思路) 然后反转结果数组
func PostOrder(root *TreeNode) []int {
if root == nil {
return nil
}
var stack = list.New()
stack.PushBack(root.Left)
stack.PushBack(root.Right)
var res = []int{}
res = append(res, root.Val)
for stack.Len() > 0 {
e := stack.Back()
stack.Remove(e)
node := e.Value.(*TreeNode) // e为Element type,值为Value,因Value为接口,需要断言
if node == nil {
continue
}
res = append(res, node.Val)
stack.PushBack(node.Left)
stack.PushBack(node.Right)
}
// 反转结果数组
for i := 0; i < len(res)/2; i++ {
res[i], res[len(res)-1-i] = res[len(res)-1-i], res[i]
}
return res
}