关闭

【LeetCode】Binary Tree Postorder Traversal

标签: leetcodeJava
724人阅读 评论(0) 收藏 举报
分类:

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].

Note: Recursive solution is trivial, could you do it iteratively?


/**
 * Definition for binary tree
 * 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> res = new ArrayList<Integer>();
		 if(root == null)
			 return res;
		 recursion(res,root);
		 return res;
    }
     public void recursion(ArrayList<Integer> res, TreeNode root)
	 {
		 if(root.left != null)
		 {
			 recursion(res,root.left);
		 }
		 if(root.right != null)
		 {
			 recursion(res,root.right);
		 }
		 res.add(root.val);
	 }
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:340233次
    • 积分:6121
    • 等级:
    • 排名:第4234名
    • 原创:270篇
    • 转载:24篇
    • 译文:0篇
    • 评论:73条
    最新评论