zoukankan      html  css  js  c++  java
  • 按之字形顺序打印二叉树

    思路:两个栈s1和s2,遍历s1时按左到右顺序在s2存放子树根节点,遍历s2时按从右到左顺序在s1存放子树根节点

    public class Solution {
        public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
            ArrayList<ArrayList<Integer>> listAll = new ArrayList<ArrayList<Integer>>();
            if(pRoot == null) return listAll;
            Stack<TreeNode> s1 = new Stack();//栈
            Stack<TreeNode> s2 = new Stack();
           
            TreeNode p = null;
           
            s1.push(pRoot);
            while(!s1.isEmpty() || !s2.isEmpty()){
                ArrayList<Integer> list = new ArrayList<>();
                while(!s1.isEmpty()){
                    p = s1.pop();
                    list.add(p.val);
                    if(p.left != null)s2.push(p.left);
                    if(p.right != null)s2.push(p.right);
                }
                if(!list.isEmpty())listAll.add(list);
                list = new ArrayList<>();
                while(!s2.isEmpty()){
                    p = s2.pop();
                    list.add(p.val);
                    if(p.right != null)s1.push(p.right);
                    if(p.left != null)s1.push(p.left);
                }
                if(!list.isEmpty())listAll.add(list);
            }
            return listAll;
           

        }

    }

  • 相关阅读:
    数据结构化与保存
    使用正则表达式,取得点击次数,函数抽离
    爬取校园新闻首页的新闻
    网络爬虫基础练习
    Hadoop综合大作业
    理解MapReduce
    熟悉常用的HBase操作
    熟悉常用的HDFS操作
    爬虫大作业
    数据结构化与保存
  • 原文地址:https://www.cnblogs.com/dyq19/p/10559998.html
Copyright © 2011-2022 走看看