zoukankan      html  css  js  c++  java
  • 剑指offer32----之字形打印一颗二叉树

    题目

    请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。

    思路

    在这里我们如果单纯的使用队列去弄的话,会很麻烦,所有这里我们使用栈结构来实现,如下图所示,我们打印的顺序应该是:1、3、2、4、5、6。

    (1)我们先把1压入到一个栈(stack1),然后取出1,这时我们把他的左右节点放到另一个栈里(stack2),因为是先打印3再2,所以我们应该从左到右压。

    (2)我们拿到刚才压2和3的栈(stack2),因为3在栈顶,所以先取出3打印,然后打印2,打印的同时也要把当前节点左右节点压入到另一个栈(stack1),因为先取出的是3,所以我们把3的左子节点压入栈,然后再压2的子节点,因为是打印顺序是456,所以我们从右到左。

    如果当两个栈都为空时,代表当前所有的节点都打印完了,所以结束。

    代码如下:

    public class Offer32 {
    	public static class TreeNode {
    		int val;
    		TreeNode left;
    		TreeNode right;
    
    		TreeNode(int x) {
    			val = x;
    		}
    	}
    
    	public static void printTree(TreeNode root) {
    		if (root == null) {
    			return;
    		}
    		Stack<TreeNode> stack1 = new Stack<>();
    		Stack<TreeNode> stack2 = new Stack<>();
    		int index = 2;
    		stack1.push(root);
    		while (stack1.size() > 0 || stack2.size() > 0) {
    			TreeNode cur = null;
    			while (index % 2 == 0 && stack1.size() > 0) {
    				// stack2负责压入层数为偶数的节点
    				cur = stack1.pop();
    				System.out.println("树节点" + cur.val);
    				// 先压左再压右
    				if (cur.left != null) {
    					stack2.push(cur.left);
    				}
    				if (cur.right != null) {
    					stack2.push(cur.right);
    				}
    			}
    			while (index % 2 != 0 && stack2.size() > 0) {
    				// stack1负责压入层数为奇数的节点
    				cur = stack2.pop();
    				System.out.println("树节点" + cur.val);
    				// 先压右再压左
    				if (cur.right != null) {
    					stack1.push(cur.right);
    				}
    				if (cur.left != null) {
    					stack1.push(cur.left);
    				}
    			}
    			index++;
    		}
    	}
    }
    

      

  • 相关阅读:
    MTK android flash配置
    MTK平台缩写
    百度员工离职总结:如何做个好员工
    android 分区layout以及虚拟内存布局-小结
    Android eMMC Booting
    Android gingerbread eMMC booting
    Chrome插件开发
    jsonp解决CORS问题
    【好玩】将js代码转为日式表情
    多行文本溢出显示省略号(...)的方法
  • 原文地址:https://www.cnblogs.com/Booker808-java/p/9279435.html
Copyright © 2011-2022 走看看