题目来源
题目概述
给你一棵二叉树的根节点 root ,返回其节点值的 后序遍历 。
思路分析
使用迭代和递归方法都可以实现二叉树的后序遍历。
代码实现
java实现
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode last = null;
while (root!= null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
if (root.right == null || root.right == last) {
res.add(root.val);
last = root;
root = null;
}else {
stack.push(root);
root = root.right;
}
}
return res;
}
}
c++实现
class Solution {
public:
vector<int> res;
vector<int> postorderTraversal(TreeNode* root) {
if (root == nullptr) {
return res;
}
postorderTraversal(root->left);
postorderTraversal(root->right);
res.push_back(root->val);
return res;
}
}