1: 二叉树的后序遍历
1.1 思路
二叉树的后序遍历的顺序是左右中,我们可以通过改造前序遍历的入栈顺顺序中左右改为中右左,只需在代码中调换左右的入栈顺序。最终结果再逆置以下就好了
1.2代码
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> res = new ArrayList<>();
if(root == null) return res;
Stack<TreeNode> stk = new Stack<>();
stk.push(root);
//前序遍历的顺序是中左右, 我们可以改成中右左 而后序是左右中 正好是其逆序
while(!stk.isEmpty()){
TreeNode temp = stk.pop();
res.add(temp.val);
if(temp.left != null) stk.push(temp.left);
if(temp.right != null) stk.push(temp.right);
}
//逆序
Collections.reverse(res);
return res;
}
}