DFS in Binary Tree(pass the depth or level in)

Convert Binary Tree to Linked Lists by Depth: http://www.lintcode.com/en/problem/convert-binary-tree-to-linked-lists-by-depth/

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 ""