Java Solution simple and easy to understands, beats 92%


  • 0
    Z
    public List<List<String>> printTree(TreeNode root) {
        int row = getDepth(root);
        int col = getColumn(row);
        List<List<String>> result = new ArrayList<>();
        for (int i = 0; i < row; i++) {
            result.add(new ArrayList<String>());
            for (int j = 0; j < col; j++) {
                result.get(i).add("");
            }
        }
        helper(result, root, 0, col / 2, col / 2);
        return result;
    }
    
    private void helper(List<List<String>> result, TreeNode root, int r, int c, int interval) {
        if (root == null) {
            return;
        }
        result.get(r).set(c, root.val + "");
        helper(result, root.left, r + 1, c - (interval - interval / 2), interval / 2);
        helper(result, root.right, r + 1, c + (interval - interval / 2), interval / 2);
    }
    
    private int getColumn(int depth) {
        int result = 1;
        for (int i = 1; i < depth; i++) {
            result = result * 2 + 1;
        }
        return result;
    }
    
    private int getDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = getDepth(root.left);
        int right = getDepth(root.right);
        return Math.max(left, right) + 1;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.