题目:
二叉树的后序遍历
给出一棵二叉树,返回其节点值的后序遍历。
样例
给出一棵二叉树 {1,#,2,3},
1
\
2
/
3
返回 [3,2,1]
挑战
你能使用非递归实现么?
解题:
递归程序好简单
Java程序:
/** * 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<Integer> postorderTraversal(TreeNode root) { // write your code here ArrayList<Integer> res = new ArrayList<Integer>(); res = postorder(res,root); return res; } public ArrayList<Integer> postorder(ArrayList<Integer> res,TreeNode root){ if(root==null) return res; if(root.left!=null) res = postorder(res,root.left); if(root.right!=null) res = postorder(res,root.right); res.add(root.val); return res; } }