题解 | #二叉树的后序遍历#
二叉树的后序遍历
https://www.nowcoder.com/practice/1291064f4d5d4bdeaefbf0dd47d78541
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型一维数组
*/
public static int[] postorderTraversal(TreeNode root){
Stack<TreeNode> stack=new Stack<>();
List<Integer> list=new ArrayList<>();
TreeNode cursor_1=root;
if(cursor_1==null){
return new int[0];
}
stack.push(cursor_1);
while(!stack.isEmpty()){
//后序遍历的话 是节点的访问顺序低于左子树和右子树
cursor_1=stack.pop();
list.add(0, cursor_1.val);
//由于这里采用的是list的头插法,所以应该先放左子树(顺序颠倒一下),这样访问顺序才是左->右->根
if(cursor_1.left!=null){
stack.push(cursor_1.left);
}
if(cursor_1.right!=null){
stack.push(cursor_1.right);
}
}
return list.stream().mapToInt(Integer::intValue).toArray();
}
}

