后序遍历二叉树

题目描述:

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;
    }
}

 

posted @ 2018-09-27 20:21  天剑含光  阅读(126)  评论(0编辑  收藏  举报