A easy and concise JavaScript solution


  • 0
    T

    The solution is pretty straightforward.

    1. Calc the height of the tree first.
    2. Construct the array according to the height
    3. Traverse the tree and put the value of each node to the right position of the 2D-array.
    function getTreeHeight(root){
        if(!root){
            return 0;
        }
        return 1 + Math.max(getTreeHeight(root.left), getTreeHeight(root.right));
    }
    
    function printTreeHelper(arr, root, idx, begin, end){
        if(!root){
            return;
        }
        
        let mid = ~~((begin + end)/2);
        arr[idx][mid] = String(root.val);
        printTreeHelper(arr, root.left, idx+1, begin, mid-1);
        printTreeHelper(arr, root.right, idx+1, mid+1, end);
    }
    
    var printTree = function(root) {
        //special case
        if(!root || root.length === 0){
            return [];
        }
        
        let height = getTreeHeight(root);
        //create ret array
        let arr = [];
        for(let i=0; i<height; i++){
            arr.push(new Array(Math.pow(2,height)-1).fill(""));
        }
        printTreeHelper(arr, root, 0, 0, Math.pow(2,height)-1);
        return arr;
    };
    

Log in to reply
 

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