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

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

    例如,给定一个 3叉树 :

     

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

    说明: 递归法很简单,你可以使用迭代法完成此题吗?

    class Solution {
        public List<Integer> res = new ArrayList<>();
        public List<Integer> preorder(Node root) {
            if(root == null) return res;
            res.add(root.val);
            for(Node node : root.children) {
                preorder(node);
            }
            return res;
        }
    }
    /*
    // Definition for a Node.
    class Node {
        public int val;
        public List<Node> children;
    
        public Node() {}
    
        public Node(int _val,List<Node> _children) {
            val = _val;
            children = _children;
        }
    };
    */
    class Solution {
        public List<Integer> preorder(Node root) {
            List<Integer> res = new ArrayList<Integer>();
            preOrder(res,root);
            return res;
        }
        public void preOrder(List<Integer> res, Node root) {
            if(root == null) return;
            res.add(root.val);
            for(int i=0; i<root.children.size(); i++) {
                preOrder(res,root.children.get(i));
            }
        }
    }
  • 相关阅读:
    检查使用的端口
    time is always agains us
    检查使用的端口
    dreque问题一例
    查看重定向的输出
    安装VSS时,Um.dat may be corrupt
    修改网卡ip
    redis install on ubuntu/debian
    上火了
    学这么多技术是为什么
  • 原文地址:https://www.cnblogs.com/Roni-i/p/10456552.html
Copyright © 2011-2022 走看看