590。 n 叉树后序遍历
难度:简单
主题: 堆栈、树、深度优先搜索
给定n叉树的根,返回其节点值的后序遍历.
nary-tree 输入序列化以其级别顺序遍历来表示。每组孩子都由空值分隔(参见示例)
示例1:

示例2:

限制:
后续: 递归解决方案很简单,你能迭代地完成吗?
解决方案:
我们可以递归和迭代地处理它。由于后续要求迭代解决方案,我们将重点关注这一点。后序遍历是指先访问子节点,再访问父节点。
让我们用 php 实现这个解决方案:590。 n 叉树后序遍历
<?php
//Definition for a Node.
class Node {
public $val = null;
public $children = [];
public function __construct($val) {
$this->val = $val;
}
}
/**
* @param Node $root
* @return integer[]
*/
function postorder($root) {
...
...
...
/**
* go to ./solution.php
*/
}
// Example 1:
$root1 = new Node(1);
$root1->children = [
$node3 = new Node(3),
new Node(2),
new Node(4)
];
$node3->children = [
new Node(5),
new Node(6)
];
print_r(postorder($root1)); // Output: [5, 6, 3, 2, 4, 1]
// Example 2:
$root2 = new Node(1);
$root2->children = [
new Node(2),
$node3 = new Node(3),
$node4 = new Node(4),
$node5 = new Node(5)
];
$node3->children = [
$node6 = new Node(6),
$node7 = new Node(7)
];
$node4->children = [
$node8 = new Node(8)
];
$node5->children = [
$node9 = new Node(9),
$node10 = new Node(10)
];
$node7->children = [
new Node(11)
];
$node8->children = [
new Node(12)
];
$node9->children = [
new Node(13)
];
$node11 = $node7->children[0];
$node11->children = [
new Node(14)
];
print_r(postorder($root2)); // Output: [2, 6, 14, 11, 7, 3, 12, 8, 4, 13, 9, 10, 5, 1]
?>
初始化:
穿越:
结果:
这种迭代方法通过使用堆栈并反转通常通过递归完成的过程来有效地模拟后序遍历。
联系链接
如果您发现本系列有帮助,请考虑在 github 上给存储库 一颗星,或在您最喜欢的社交网络上分享该帖子?。您的支持对我来说意义重大!
如果您想要更多类似的有用内容,请随时关注我:
以上就是N 叉树邮购遍历的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号