4.4---建立二叉树的链表

public class TreeLevel {
     public ListNode getTreeLevel(TreeNode root, int dep) {
        // write code here
        List<TreeNode> result = new ArrayList();
        ListNode res = null;
        if(root == null || dep <= 0    ){
            return res;
        }
        result.add(root);
        if(dep == 1){
            res = new ListNode(root.val);
            return res;
        }
        
        while(dep > 1){
            List<TreeNode> temp = new ArrayList();
            for(TreeNode t : result){
                if(t.left != null) temp.add(t.left);
                if(t.right != null) temp.add(t.right);
            }
            result = temp;
            dep--;
        }
        
        res = new ListNode(result.get(0).val);
        ListNode temp = res;
        for(int i = 1; i < result.size(); i++){
            temp.next = new ListNode(result.get(i).val);
            temp = temp.next;
        }
        return res;
    }
}

 

posted @ 2015-12-22 20:36  创业-李春跃-增长黑客  阅读(211)  评论(0编辑  收藏  举报