简体   繁体   中英

Print binary tree recursive function

I'm attempting to return an array of arrays that represents a binary tree. I created an output array filled with arrays of empty strings, where each array represents one level of the tree and the strings represent each possible node position on that level. For some reason, it looks like my recursive function is making changes to all arrays in my parent output array, rather than just the appropriate one.

var printTree = function(root) {
//first find depth of tree
    let depth = 0
    const findDepth = (node, level) => {
        depth = Math.max(depth, level);
        if (node.left) {
            findDepth(node.left, level + 1)
        }
        if (node.right) {
            findDepth(node.right, level + 1)
        }
    }
    findDepth(root, 1);
    let width = 1 + ((depth - 1) * 2)
//create array of arrays filled with blanks that match height and width
// of given tree
    let output = new Array(depth).fill(new Array(width).fill(''));
    let mid = Math.floor(width / 2);
//do DFS through tree and change output array based on position in tree
    const populate = (node, level, hori) => {
        output[level][hori] = node.val;
        if (node.left) {
            populate(node.left, level + 1, hori - 1);
        }
        if (node.right) {
            populate(node.right, level + 1, hori + 1);
        }
    }
    populate(root, 0, mid);
    return output;
};

If I put in a binary tree with a root node with the val of 1, and its only child is left with a val of 2.

My output array should be:

[['', 1 , ''],
[2 , '' , '']]

But instead it looks like this:

[[2, 1, ''],
[2, 1, '']]

I have console logged the recursive calls and I can't figure out why these changes are being made in all rows of my matrix and not just at the appropriate level.

How do I solve this problem?

You need to change this line

let output = new Array(depth).fill(new Array(width).fill(''));
//                                 ^^^^^^^^^^^^^^^^^^^^^^^^^ same array!

into

let output = Array.from({ length: depth }, _ => Array.from({ length: width }).fill(''));

because you fill the array with the same array. The underlined part fills with the same array, a constant value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM