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

    题目描述

    请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
     1 import java.util.ArrayList;
     2 import java.util.Stack;
     3 
     4 /*
     5 public class TreeNode {
     6     int val = 0;
     7     TreeNode left = null;
     8     TreeNode right = null;
     9 
    10     public TreeNode(int val) {
    11         this.val = val;
    12 
    13     }
    14 
    15 }
    16 */
    17 public class Solution {
    18     public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
    19         
    20         Stack<TreeNode> []level = new Stack[2];
    21         level[0] = new Stack<TreeNode>();
    22         level[1] = new Stack<TreeNode>();
    23         ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
    24         if (pRoot == null) return ans;
    25         level[0].push(pRoot);
    26         int now = 0;
    27         ArrayList<Integer> l = new ArrayList<>();
    28         int num = 0;
    29         while (!level[0].empty() || !level[1].empty()) {
    30             TreeNode temp = level[now].pop();
    31             l.add(temp.val);
    32             int next = (now + 1) % 2;
    33             if (num % 2 == 0) {
    34                 if (temp.left != null) {
    35                     level[next].push(temp.left);
    36                 }
    37                 if (temp.right != null){
    38                     level[next].push(temp.right);
    39                 }
    40                 
    41             } else {
    42                 if (temp.right != null){
    43                     level[next].push(temp.right);
    44                 }
    45                 if (temp.left != null) {
    46                     level[next].push(temp.left);
    47                 }
    48                 
    49             }
    50             if (level[now].empty()) {
    51                 now = (now + 1) % 2;
    52                 num++;
    53                 ans.add(new ArrayList<Integer>(l));
    54                 l = new ArrayList<>();
    55             }
    56             
    57             
    58         }
    59         return ans;
    60     }
    61 
    62 }
  • 相关阅读:
    sort函数详解
    C++重载运算符的规则详解
    poj3061-subsequence
    员工管理系统 :练习
    Jdbc 模拟登陆系统的练习
    有关String 的常用方法
    浅谈希尔排序-----摘录
    简单选择排序
    typedef 和define 的区别
    写博客的理由
  • 原文地址:https://www.cnblogs.com/hyxsolitude/p/12340203.html
Copyright © 2011-2022 走看看