LintCode-68.二叉树的后序遍历

题目

描述

给出一棵二叉树,返回其后序遍历

样例

给出二叉树 {1,#,2,3},

   1
    \
     2
    /
   3

返回 [3,2,1].

解答

思路

后序遍历二叉树

代码

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Postorder in ArrayList which contains node values.
     */
    public ArrayList postorderTraversal(TreeNode root) {
        // write your code here
        ArrayList a = new ArrayList();
        postOrder(a, root);
        return a;
    }
        
    private void postOrder(ArrayList a, TreeNode root){
        if(root == null) return;
        postOrder(a, root.left);
        postOrder(a, root.right);
        a.add(root.val);
    }
}

你可能感兴趣的:(LintCode-68.二叉树的后序遍历)