当前位置:   article > 正文

leetcode刷题笔记之Tree专题记录_trre的题

trre的题

Tree

N叉树遍历总结

后序遍历

```python3
"""
# Definition for a Node.
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children
"""

class Solution:
    def postorder(self, root: 'Node') -> List[int]:
        if root == None:  #如果根节点不存在
            return []     #返回空数组
        stack , out = [root,],[]  #创建stack(栈)以及out数组
        while stack:     #stack数组存在节点
            root = stack.pop()  #将栈顶节点取出赋给根节点
            if root:            #如果根节点存在
                out.append(root.val) #将根节点的值加入到out数组中
            for c in root.children:  #遍历根节点下的孩子节点
                stack.append(c)  #将遍历的孩子节点加入到栈中
        return out[::-1]         #返回逆序out数组
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

236.二叉树的最近公共祖先

class Solution:
    def lowestCommonAncestor(self
  • 1
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/788874
推荐阅读
相关标签
  

闽ICP备14008679号