gpt4 book ai didi

打印二叉树左 View 的 JavaScript 实现返回错误结果

转载 作者:行者123 更新时间:2023-12-03 08:05:15 25 4
gpt4 key购买 nike

我正在尝试打印二叉树的左 View ,如here所示关于geeksforgeeks。由于某种原因它不起作用,我怀疑它与 max_level 有关。结果是 [ 12, 10, 30, 25, 40 ],我期待 [12,10,25]

JS代码

var Node = function(val) {
this.val = val;
this.left = this.right = null;
};

var leftViewUtil = function(root, level, max, result) {
if (root === null) return;

if (max.level < level) {
max.level = level;
result.arr.push(root.val);
}

leftViewUtil(root.left, ++level, max, result);
leftViewUtil(root.right, ++level, max, result);
};

var leftView = function(root) {
var result = {
arr: []
};

var max_level = {level: 0};

leftViewUtil(root, 1, max_level, result);

return result.arr;
};

root = new Node(12);
root.left = new Node(10);
root.right = new Node(30);
root.right.left = new Node(25);
root.right.right = new Node(40);

var run = function() {
console.log(leftView(root));
};

run();

最佳答案

链接页面上的代码之间的差异是

// Recur for left and right subtrees
leftViewUtil(root->left, level+1, max_level);
leftViewUtil(root->right, level+1, max_level);

对比

leftViewUtil(root.left, ++level, max, result);
leftViewUtil(root.right, ++level, max, result);

您在这里将 level 增加两次,同时您应该将相同的值传递给两个递归调用。适当使用 level+1 ,或者在调用之前进行增量:

++level;
leftViewUtil(root.left, level, max, result);
leftViewUtil(root.right, level, max, result);

关于打印二叉树左 View 的 JavaScript 实现返回错误结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34406698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com