【问题标题】:View of a binary tree from 45 degree从 45 度看二叉树
【发布时间】:2018-05-04 17:51:52
【问题描述】:
所以我不是在问一棵树的对角线视图,幸运的是我已经知道了。我在问我是否从 45 度角查看一棵树,只有几个节点应该可见。所以有一个平面与 x 轴成 45 度角。所以我们需要打印从该平面可见的所有节点。
例如:
1
/ \
2 3
/ \ / \
4 5 6 7
所以如果我从那个平面看,我只会看到节点 [4, 6, 7] 因为 5 和 6 相互重叠。如果我在 6 处添加另一个节点,现在它将隐藏 7。如何做到这一点?我在互联网上搜索但找不到答案。
谢谢!
【问题讨论】:
标签:
data-structures
binary-tree
tree-traversal
【解决方案1】:
我给你一个抽象的答案,因为这个问题不是特定语言的。
像这样记录树的问题在于递归的使用。
我的意思是遍历是向下节点和向上节点。
如果你写了一个高度帮助器,它会返回当前节点的深度。
对于每个深度级别,您将值放在一个数组中。
然后,写入数组的值。
然后您可以获取最后一个数组的长度并确定每个节点需要的空间量。
允许数组保存空值,否则您将不得不跟踪哪些节点没有子节点。
int total_depth = tree.getTotalHeight();
int arr[total_depth] = {};
for(int i = total_depth; i--;){
// there is a formula for the max number of nodes at a given depth of a binary tree
arr[i] = int arr[maximum_nodes_at_depth]
}
tree.inorderTraverse(function(node){
int depth = node.getHeightHelper();
// check if item is null
if( node!=nullptr && node.Item != NULL)
{
arr[depth].push(node.Item)
}
else
{
arr[depth].push(NULL)
}
})
所以现在你必须计算你的树的大小,然后动态计算每个节点前应该有多少空格。深度越低,居中的前缀空格就越多。
我很抱歉,但伪代码是 javascript 和 c++ 语法的混合......这永远不会发生,哈哈