Convert Binary Tree to Linked Lists by Depth

http://lintcode.com/en/problem/convert-binary-tree-to-linked-lists-by-depth/

/**
 * 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;
 *     }
 * }
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    /**
     * @param root the root of binary tree
     * @return a lists of linked list
     */
    public List<ListNode> binaryTreeToLists(TreeNode root) {
        // Write your code here
        List<ListNode> result = new ArrayList<ListNode>();
        dfs(root, 1, result);
        return result;
    }

    void dfs(TreeNode root, int depth, List<ListNode> result) {
        if(root == null){
            return;
        }    

        ListNode node = new ListNode(root.val);
        if(result.size() < depth){
            result.add(node);
        }else{
            node.next = result.get(depth - 1);
            result.set(depth - 1, node);
        }

        dfs(root.right, depth + 1, result);
        dfs(root.left, depth + 1, result);
    }
}

results matching ""

    No results matching ""