java - 如何返回按顺序遍历指定子树(指定节点的左子树或右子树)的数组
问题描述
我使用递归函数实现它,如下所示。我很确定我以正确的顺序实现它,但是我似乎未能通过我的测试用例,有人可以指出我的代码哪里出了问题吗?
/**
* Build an array of nodes in the specified subtree.
*
* @param node the parent node, not to be included in returned array
* @param child the specified subtree
* @return array of nodes
*/
//countNodes return the total number of nodes in the subtree excluding the parent node
public TreeNode[] enumerateNodes(TreeNode node, Child child) {
TreeNode[] treeNodes = new TreeNode[countNodes(node, child)];
if(child == Child.RIGHT) {
node = node.right;
}
if(child == Child.LEFT) {
node = node.left;
}
enumerateNodes(node, treeNodes, 0);
return treeNodes;
}
private void enumerateNodes(TreeNode node, TreeNode[] arrays, int cur){
if(node == null){
return;
}
enumerateNodes(node.left, arrays, cur);
arrays[cur++] = node;
enumerateNodes(node.right, arrays, cur);
}
解决方案
H
/ --- \
L1 ---- R1
/ \ ------ / \
L2
抱歉这棵丑陋的树,但是当你向左走时,你会看到 L1 的左孩子的空 ptr 是 L2。你上去,叫这个:
arrays[cur++] = node;
现在 cur 得到 0,数组将 L2 作为第一个节点(索引 0)。将递增到 1。使用正确的值向右移动。到目前为止一切都很好。
然而。当你用尽左子树时。您将转到右子树(带有头 R)。
array[0] = L1 // this will override L2
推荐阅读
- r - 连接 2 个数据集,其中关键变量出现在左右数据集中的多行中:R
- python - Pandas 用字典替换不适用于 CSV 文件
- jquery - jQuery悬停2个元素
- javascript - 如何在最小值和最大值之间对齐范围滑块中的数据标签
- optaplanner - OptaPlanner,构建需要从解决方案中获取信息的规则
- flyway - 有什么方法可以根据已安装的排名而不是版本撤消 Flyway 吗?
- reactjs - 在 React 中没有从 useHistory 接收道具
- python - Python/Pandas Str.split 在没有拆分时返回 NAN
- spring-boot - 如何跟踪用户活动并将其发送到数据库
- regex - 如果字符串包含列表中的单词,则从字符串中提取单词