资讯专栏INFORMATION COLUMN

Leetcode PHP题解--D55 429. N-ary Tree Level Order Tr

libxd / 3429人阅读

摘要:题目链接题目分析按层遍历叉树。思路以层数为键,塞入当前节点的值。最终代码若觉得本文章对你有用,欢迎用爱发电资助。

D55 429. N-ary Tree Level Order Traversal 题目链接

429. N-ary Tree Level Order Traversal

题目分析

按层遍历N叉树。

思路

以层数为键,塞入当前节点的值。

递归遍历即可。

最终代码

</>复制代码

  1. $children
  2. function __construct($val, $children) {
  3. $this->val = $val;
  4. $this->children = $children;
  5. }
  6. }
  7. */
  8. class Solution {
  9. /**
  10. * @param Node $root
  11. * @return Integer[][]
  12. */
  13. public $level = 0;
  14. public $values = [];
  15. function levelOrder($root) {
  16. if(is_null($root)){
  17. return $this->values;
  18. }
  19. if(!isset($this->values[$this->level])){
  20. $this->values[$this->level] = [];
  21. }
  22. $this->values[$this->level][] = $root->val;
  23. foreach($root->children as $child){
  24. $this->level++;
  25. $this->levelOrder($child);
  26. $this->level--;
  27. }
  28. return $this->values;
  29. }
  30. }

若觉得本文章对你有用,欢迎用爱发电资助。

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/31401.html

相关文章

  • [LeetCode] 429. N-ary Tree Level Order Traversal (

    429. N-ary Tree Level Order Traversal Given an n-ary tree, return the level order traversal of its nodes values. (ie, from left to right, level by level). For example, given a 3-ary tree:showImg(https...

    LiangJ 评论0 收藏0
  • leetcode429. N-ary Tree Level Order Traversal

    摘要:题目要求对叉树进行水平遍历,并输出每一行遍历的结果。因此无需再用队列来额外存储每一行的水平遍历,可以直接通过递归将遍历结果插入到相应行的结果集中。 题目要求 Given an n-ary tree, return the level order traversal of its nodes values. (ie, from left to right, level by level)...

    tomlingtm 评论0 收藏0
  • Leetcode PHP题解--D42 559. Maximum Depth of N-ary Tr

    摘要:题目链接题目分析此题和上一题思路一样。只是不是二叉树。思路略最终代码若觉得本文章对你有用,欢迎用爱发电资助。 D42 559. Maximum Depth of N-ary Tree 题目链接 559. Maximum Depth of N-ary Tree 题目分析 此题和上一题思路一样。只是不是二叉树。而是正常的树。 思路 略 最终代码

    CrazyCodes 评论0 收藏0
  • Leetcode PHP题解--D43 589. N-ary Tree Preorder Trave

    摘要:题目链接题目分析维数组的先序遍历。这题也不想多说什么了。是比较基础的题目了。先序就是先根后子而已。思路在遍历子节点之前,先保存当前节点的信息。最终代码若觉得本文章对你有用,欢迎用爱发电资助。 D43 589. N-ary Tree Preorder Traversal 题目链接 589. N-ary Tree Preorder Traversal 题目分析 N维数组的先序遍历。 这题也...

    junbaor 评论0 收藏0
  • Leetcode PHP题解--D44 590. N-ary Tree Postorder Trav

    摘要:题目链接题目分析后序遍历,这题也是比较基础的题目了。思路先遍历子节点,再遍历根节点。最终代码若觉得本文章对你有用,欢迎用爱发电资助。 D44 590. N-ary Tree Postorder Traversal 题目链接 590. N-ary Tree Postorder Traversal 题目分析 后序遍历,这题也是比较基础的题目了。 思路 先遍历子节点,再遍历根节点。 最终代码...

    Songlcy 评论0 收藏0

发表评论

0条评论

libxd

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<