javascript - 任意树的高度
问题描述
给定一棵任意树,其中每个节点都有一个指向其第一个子节点 ( node.left
) 及其最近的兄弟节点 ( ) 的指针node.right
,如何找到树的高度?
这就是我所拥有的:
function height(tree) {
let h = 0;
const queue = [[tree.root, 1]]; // pair (Node, depth)
let n = 0; // use a pointer rather than shifting the array
while (n < queue.length) {
const [node, d] = queue[n];
if (d > h) h = d; // if the current depth is greater then the max height so far, then update the max height
// Traverse the siblings
let r = node.right;
while (r) {
queue.push([r, d]); // siblings have the same depth
r = r.right;
}
node.left && queue.push([node.left, d + 1]); // traverse the children
n++; // go to the next Node
}
return h;
}
它不是递归的,因为树可能真的很大而且我得到溢出错误。这段代码应该可以工作,但只是想知道是否有不同/更好的方法来做到这一点。
解决方案
function height(node){
if(!node) return 0;
var leftHeight = height(node.left);
var rightHeight = height(node.right);
return Math.max(leftHeight, rightHeight) + 1;
}
最好的方法是使用递归。它干净易读。
推荐阅读
- json - 列“IMAGE BINARY(255)”的值太长
- node.js - node.js express 路由在远程服务器中不起作用
- c# - 使用 Visual Studio 2017 构建的 .NET 4.7.2 C# 控制台应用程序的 ILRepack 需要在 Windows 7 上安装框架
- node.js - 将前端应用程序与服务器连接时出现问题
- python - 如何在熊猫中分析时间序列数据作为一天中时间的函数
- symfony - 从数组中读取对象
- html - 我想更改 Bootstrap 导航栏的背景颜色。
- php - 在 Symfony 中运行一个独立的无休止的工作
- typescript - 打字稿找不到本地链接的模块?
- java - 在 Java 后端和 Android 应用程序之间共享 POJO