【LeetCode從零單排】No102 Binary Tree Level Order Traversal

李博Garvin發表於2015-03-03

題目

       

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]

基本二叉樹這塊用的都是遞迴,現在還是有點蒙。

程式碼

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> al=new ArrayList<List<Integer>>();
        levelHelper(al,root,0);
        return al;
        
    }
    public void levelHelper(List<List<Integer>> res,TreeNode root,int height){
        if(root==null) return;
        if(height>=res.size()){
            res.add(new ArrayList<Integer>());
            
    }
        res.get(height).add(root.val);
        levelHelper(res,root.left,height+1);
        levelHelper(res,root.right,height+1);

 }
}    


/********************************

* 本文來自部落格  “李博Garvin“

* 轉載請標明出處:http://blog.csdn.net/buptgshengod

******************************************/



相關文章