给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3] 1 \ 2 / 3 输出: [3,2,1]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
1. 递归遍历
先递归左右子树,再访问根节点。
2. 栈实现非递归遍历
非递归的思路如下:
先序遍历的顺序是:头、左、右,如果我们改变左右孩子的顺序,就能将顺序变成:头、右、左。
我们先不打印头节点,而是存放到另一个收集栈 res 中,最后遍历结束,输出收集栈元素,即是后序遍历:左、右、头。收集栈是为了实现结果列表的逆序。我们也可以直接使用链表,每次插入元素时,放在头部,最后直接返回链表即可,无需进行逆序。
3. Morris 实现后序遍历
Morris 遍历无需使用栈,空间复杂度为 O(1)。核心思想是:
遍历二叉树节点,
- 若当前节点 root 的右子树为空,将当前节点值添加至结果列表 res 中,并将当前节点更新为
root.left
- 若当前节点 root 的右子树不为空,找到右子树的最左节点 next(也即是 root 节点在中序遍历下的后继节点):
- 若后继节点 next 的左子树为空,将当前节点值添加至结果列表 res 中,然后将后继节点的左子树指向当前节点 root,并将当前节点更新为
root.right
。 - 若后继节点 next 的左子树不为空,将后继节点左子树指向空(即解除 next 与 root 的指向关系),并将当前节点更新为
root.left
。
- 若后继节点 next 的左子树为空,将当前节点值添加至结果列表 res 中,然后将后继节点的左子树指向当前节点 root,并将当前节点更新为
- 循环以上步骤,直至二叉树节点为空,遍历结束。
- 最后返回结果列表的逆序即可。
Morris 后序遍历跟 Morris 前序遍历思路一致,只是将前序的“根左右”变为“根右左”,最后逆序结果即可变成“左右根”。
递归:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
res = []
def postorder(root):
if root:
postorder(root.left)
postorder(root.right)
res.append(root.val)
postorder(root)
return res
栈实现非递归:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
res = []
if root:
s = [root]
while s:
node = s.pop()
res.append(node.val)
if node.left:
s.append(node.left)
if node.right:
s.append(node.right)
return res[::-1]
Morris 遍历:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
res = []
while root:
if root.right is None:
res.append(root.val)
root = root.left
else:
next = root.right
while next.left and next.left != root:
next = next.left
if next.left is None:
res.append(root.val)
next.left = root
root = root.right
else:
next.left = None
root = root.left
return res[::-1]
递归:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
postorder(root, res);
return res;
}
private void postorder(TreeNode root, List<Integer> res) {
if (root != null) {
postorder(root.left, res);
postorder(root.right, res);
res.add(root.val);
}
}
}
栈实现非递归:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
LinkedList<Integer> res = new LinkedList<>();
if (root != null) {
Deque<TreeNode> s = new LinkedList<>();
s.offerLast(root);
while (!s.isEmpty()) {
TreeNode node = s.pollLast();
res.addFirst(node.val);
if (node.left != null) {
s.offerLast(node.left);
}
if (node.right != null) {
s.offerLast(node.right);
}
}
}
return res;
}
}
Morris 遍历:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
LinkedList<Integer> res = new LinkedList<>();
while (root != null) {
if (root.right == null) {
res.addFirst(root.val);
root = root.left;
} else {
TreeNode next = root.right;
while (next.left != null && next.left != root) {
next = next.left;
}
if (next.left == null) {
res.addFirst(root.val);
next.left = root;
root = root.right;
} else {
next.left = null;
root = root.left;
}
}
}
return res;
}
}
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function postorderTraversal(root: TreeNode | null): number[] {
if (root == null) return [];
let stack = [];
let ans = [];
let prev = null;
while (root || stack.length) {
while (root) {
stack.push(root);
root = root.left;
}
root = stack.pop();
if (!root.right || root.right == prev) {
ans.push(root.val);
prev = root;
root = null;
} else {
stack.push(root);
root = root.right;
}
}
return ans;
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
vector<int> res;
while (root)
{
if (root->right == nullptr)
{
res.push_back(root->val);
root = root->left;
}
else
{
TreeNode *next = root->right;
while (next->left && next->left != root)
{
next = next->left;
}
if (next->left == nullptr)
{
res.push_back(root->val);
next->left = root;
root = root->right;
}
else
{
next->left = nullptr;
root = root->left;
}
}
}
reverse(res.begin(), res.end());
return res;
}
};
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func postorderTraversal(root *TreeNode) []int {
var res []int
for root != nil {
if root.Right == nil {
res = append([]int{root.Val}, res...)
root = root.Left
} else {
next := root.Right
for next.Left != nil && next.Left != root {
next = next.Left
}
if next.Left == nil {
res = append([]int{root.Val}, res...)
next.Left = root
root = root.Right
} else {
next.Left = nil
root = root.Left
}
}
}
return res
}