题目地址:Binary Tree Postorder Traversal - LeetCode
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]
Follow up: Recursive solution is trivial, could you do it iteratively?
经典的二叉树后续遍历,最简单的递归做法。
Python解法如下:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
def helper(root, l):
if root is None:
return
helper(root.left, l)
helper(root.right, l)
l.append(root.val)
l = []
helper(root, l)
return l
迭代做法要麻烦一点,不容易想到。
比较好的做法是先序遍历的结果反向输出。
Python解法如下:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
if root is None:
return []
stack, output = [root, ], []
while stack:
root = stack.pop()
output.append(root.val)
if root.left is not None:
stack.append(root.left)
if root.right is not None:
stack.append(root.right)
return output[::-1]
时间复杂度为O(n),空间复杂度为O(1)。
C++解法如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
vector<int> result;
stack<TreeNode *> l;
if (root == nullptr) {
return result;
}
l.push(root);
while (!l.empty()) {
auto curr = l.top();
l.pop();
result.push_back(curr->val);
if (curr->left != nullptr) {
l.push(curr->left);
}
if (curr->right != nullptr) {
l.push(curr->right);
}
}
std::reverse(result.begin(), result.end());
return result;
}
};