zoukankan      html  css  js  c++  java
  • 非递归遍历N-ary树Java实现

    2019-03-25 14:10:51

    非递归遍历二叉树的Java版本实现之前已经进行了总结,这次做的是非递归遍历多叉树的Java版本实现。

    在非递归遍历二叉树的问题中我个人比较推荐的是使用双while的方式来进行求解,因为这种方法比较直观,和遍历的顺序完全对应。

    但是在非递归遍历多叉树的时候,使用双while方法虽然依然可行,但是就没有那么方便了。

    一、N-ary Tree Preorder Traversal

    问题描述:

    问题求解:

        public List<Integer> preorder(Node root) {
            if (root == null) return new ArrayList<>();
            List<Integer> res = new ArrayList<>();
            Stack<Node> stack = new Stack<>();
            stack.push(root);
            while (!stack.isEmpty()) {
                Node cur = stack.pop();
                res.add(cur.val);
                for (int i = cur.children.size() - 1; i >= 0; i--) if (cur.children.get(i) != null) stack.push(cur.children.get(i));
            }
            return res;
        }
    

    二、N-ary Tree Postorder Traversal

    问题描述:

    问题求解:

    public List<Integer> postorder(Node root) {
            if (root == null) return new ArrayList<>();
            List<Integer> res = new ArrayList<>();
            Stack<Node> stack = new Stack<>();
            stack.push(root);
            while (!stack.isEmpty()) {
                Node cur = stack.pop();
                res.add(0, cur.val);
                for (int i = 0; i < cur.children.size(); i++) if (cur.children.get(i) != null)
                    stack.push(cur.children.get(i));
            }
            return res;
        }
    

     

    三、N-ary Tree Level Order Traversal

    问题描述:

    问题求解:

        public List<List<Integer>> levelOrder(Node root) {
            if (root == null) return new ArrayList<>();
            List<List<Integer>> res = new ArrayList<>();
            Queue<Node> q = new LinkedList<>();
            q.offer(root);
            while (!q.isEmpty()) {
                int size = q.size();
                res.add(new ArrayList<>());
                for (int i = 0; i < size; i++) {
                    Node cur = q.poll();
                    res.get(res.size() - 1).add(cur.val);
                    for (int j = 0; j < cur.children.size(); j++) {
                        if (cur.children.get(j) != null) q.offer(cur.children.get(j));
                    }
                }
            }
            return res;
        }
    

      

     

  • 相关阅读:
    给伪类设置z-index= -1;
    UITextView的字数限制 及 添加自定义PlaceHolder
    UIView 翻转动画
    viewController的自动扩展属性导致TableViewGroupStyle时向上填充
    指针属性直接赋值 最好先retain 否则内存释放导致crash
    UIButton 点击后变灰
    IOS 设置透明度导致底层View始终可见
    UIDatePicker 时间选择器
    放大Button热区的方法哟
    数组套字典排序
  • 原文地址:https://www.cnblogs.com/hyserendipity/p/10593528.html
Copyright © 2011-2022 走看看