zoukankan      html  css  js  c++  java
  • [leetCode]589. N叉树的前序遍历

    题目

    https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/

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

    例如,给定一个 3叉树 :
    在这里插入图片描述

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

    递归

    class Solution {
        List<Integer> ans = new ArrayList<>();
    
        public List<Integer> preorder(Node root) {
            traversal(root);
            return ans;
        }
    
        private void traversal(Node node) {
            if (node == null) 
                return;
            ans.add(node.val);
            for (Node c : node.children) {
                traversal(c);
            }
        }
    }
    

    迭代

    class Solution {
        List<Integer> ans = new ArrayList<>();
    
        public List<Integer> preorder(Node root) {
            if (root == null) return ans;
            LinkedList<Node> stack = new LinkedList<>();
            stack.push(root);
            while (!stack.isEmpty()) {
                Node node = stack.pop();
                if (node != null) {
                    for (int i = node.children.size() -1; i >= 0; i--) {
                        if (node.children.get(i) != null)
                            stack.push(node.children.get(i));
                    }
                    stack.push(node);
                    stack.push(null);
                } else {
                    Node cur = stack.pop();
                    ans.add(cur.val);
                }
            }
            return ans;
        }
    }
    
  • 相关阅读:
    poj2263
    poj2304
    低调是态度,也是智慧
    股票操作記錄2
    治病記錄(2013年)
    过年了
    治病記錄
    近段時間學習記錄
    新的一年
    關于設計
  • 原文地址:https://www.cnblogs.com/PythonFCG/p/13907235.html
Copyright © 2011-2022 走看看