binary-tree-postorder-traversal

来源:互联网 发布:学闽南话的软件 编辑:程序博客网 时间:2024/04/28 10:54

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

For example:
Given binary tree{1,#,2,3},

   1    \     2    /   3

return[3,2,1].


public class TreeNode {int val;TreeNode left;TreeNode right;TreeNode(int x) { val = x; }}

public class Solution {    public ArrayList<Integer> postorderTraversal(TreeNode root) {        ArrayList<Integer> list = new ArrayList<Integer>();if(root == null)return list;Stack<TreeNode> stack1 = new Stack<TreeNode>();Stack<TreeNode> stack2 = new Stack<TreeNode>();stack1.push(root);while(!stack1.isEmpty()) {TreeNode current = stack1.pop();stack2.push(current);if(current.left != null)stack1.push(current.left);if(current.right!= null)stack1.push(current.right);}while(!stack2.isEmpty()) list.add(stack2.pop().val);return list;        }}


0 0
原创粉丝点击