后序遍历二叉树

题目描述:

Given a binary tree, return the postorder traversal of its nodes' values.

思路:利用栈,以及头插法进行操作

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.*;
public class Solution {
    public ArrayList<Integer> postorderTraversal(TreeNode root) {
        ArrayList<Integer> list=new ArrayList<>();
        Stack<TreeNode> stack=new Stack();
        if(root==null) 
            return list;
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode node=stack.pop();
            list.add(0,node.val);
            if(node.left!=null)
                stack.push(node.left);
            if(node.right!=null)
                stack.push(node.right);
        }
        return list;
    }
}
原文地址:https://www.cnblogs.com/whu-2017/p/9715348.html