N叉树的后续遍历

此博客链接:https://www.cnblogs.com/ping2yingshi/p/12945132.html

N叉树的后续遍历(76min)

题目链接:https://leetcode-cn.com/problems/n-ary-tree-postorder-traversal/

给定一个 N 叉树,返回其节点值的后序遍历

例如,给定一个 3叉树 :

 

返回其后序遍历: [5,6,3,2,4,1].

题解:

          思路:

                   1.定义一个栈存放跟节点。

                   2.遍历跟节点的孩子存入栈中,孩子节点存在则把孩子节点存入到栈中,一直递归直到没有孩子节点。

代码如下:

class Solution {
    public List<Integer> postorder(Node root) {
         LinkedList <Node> stack = new LinkedList<>();
        LinkedList<Integer> result = new LinkedList<>();
        if (root == null) {
            return result;
        }

      stack.add(root);
      while (!stack.isEmpty()) {
          Node node = stack.pollLast();
          result.addFirst(node.val);
          for (Node item : node.children) {
              if (item != null) {
                  stack.add(item);    
              } 
          }
      }
      return result;


    }
}

猜你喜欢

转载自www.cnblogs.com/ping2yingshi/p/12945132.html