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

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

    例如,给定一个 3叉树 :

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

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

    ### C#代码
    /*
    // Definition for a Node.
    public class Node {
        public int val;
        public IList<Node> children;
    
        public Node() {}
    
        public Node(int _val) {
            val = _val;
        }
    
        public Node(int _val,IList<Node> _children) {
            val = _val;
            children = _children;
        }
    }
    */
    
    public class Solution {
        public IList<int> Preorder(Node root) {
            IList<int> list = new List<int>();
            if(root == null) return list;
    
            Stack<Node> stack = new Stack<Node>();
            stack.Push(root);
    
            while(stack.TryPop(out Node node)){
                list.Add(node.val);
                int count = node.children.Count;
                while(--count > -1){
                    stack.Push(node.children[count]);
                }
            }
            return list;
        }
    }
    
  • 相关阅读:
    基于typora编写Markdown文档
    VMware Workstation常见的故障处理
    VMware Workstation产品常用的快捷键
    2
    1
    9
    8
    7
    6
    5
  • 原文地址:https://www.cnblogs.com/fuxuyang/p/14244706.html
Copyright © 2011-2022 走看看