N 叉树邮购遍历

590。 n 叉树后序遍历

难度:简单

主题: 堆栈、树、深度优先搜索

给定n叉树的根,返回其节点值的后序遍历.

nary-tree 输入序列化以其级别顺序遍历来表示。每组孩子都由空值分隔(参见示例)

示例1:

输入: root = [1,null,3,2,4,null,5,6] 输出: [5,6,3,2,4,1]

示例2:

输入: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13 ,空,空,14] 输出: [2,6,14,11,7,3,12,8,4,13,9,10,5,1]

限制:

树中节点的数量在 [0, 1青狐资源网wcqh.cn004] 范围内。 -100 4 n叉树的高度小于等于1000。

后续: 递归解决方案很简单,你能迭代地完成吗?

解决方案:

我们可以递归和迭代地处理它。由于后续要求迭代解决方案,我们将重点关注这一点。后序遍历是指先访问子节点,再访问父节点。

让我们用 php 实现这个解决方案:590。 n 叉树后序遍历

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

<青狐资源网wcqh.cn?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-&gt;children = 青狐资源网wcqh.cn[

$node3 = new Node(3),

new Node(2),

new Node(4)

];

$node3-&gt;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-&gt;children = [

new Node(2),

$node3 = new Node(3),

$node4 = new Node(4),

$node5 = new Node(5)

];

$node3-&gt;chil青狐资源网wcqh.cndren = [

$node6 = new Node(6),

$node7 = new Node(7)

];

$node4-&gt;children = [

$node8 = new Node(8)

];

$node5-&gt;children = [

$node9 = new Node(9),

$node10 = new Node(10)

];

$node7-&gt;children = [

new Node(11)

];

$node8-&gt;children = [

new Node(12)

];

$node9-&gt;children = [

new Node(13)

];

$node11 = $node7-&gt;chil青狐资源网wcqh.cndren[0];

$node11-&gt;children = [

new Node(14)

];

print_r(postorder($root2)); // Output: [2, 6, 14, 11, 7, 3, 12, 8, 4, 13, 9, 10, 5, 1]

?&gt;

登录后复制

解释:

初始化:

创建一个堆栈并将根节点压入其中。 创建一个空数组结果来存储最终的后序遍历。

穿越:

从堆栈中弹出节点,将其值插入到结果数组的开头。 将其所有子项推入堆栈。 继续直到堆栈为空。

结果

循环结束后,结果数组将包含后序的节点。

这种迭代方法通过使用堆栈并反转通常通过递青狐资源网wcqh.cn归完成的过程来有效地模拟后序遍历。

联系链接

如果您发现本系列有帮助,请考虑在 github 上给存储库 一颗星,或在您最喜欢的社交网络上分享该帖子?。您的支持对我来说意义重大!

如果您想要更多类似的有用内容,请随时关注我:

领英 github

以上就是N 叉树邮购遍历的详细内容,更多请关注青狐资源网其它相关文章!

© 版权声明
THE END
喜欢就支持一下吧
点赞149 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容