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

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
    		List<List<Integer>> ans = new ArrayList<>();
    		if (root == null)
    			return ans;
    		// 使用两个栈维护顺序
    		Stack<TreeNode> stack = new Stack<>();
    		Stack<TreeNode> nextStack = new Stack<>();
    		stack.add(root);
    		int flag = 0;
    		List<Integer> lay = new ArrayList<>();
    		while (!stack.isEmpty()) {
    			TreeNode node = stack.pop();
    			lay.add(node.val);
    			// 如果当前是从左到右遍历,按左子树右子树的顺序添加
    			if (flag == 0) {
    				if (node.left != null)
    					nextStack.add(node.left);
    				if (node.right != null)
    					nextStack.add(node.right);
    			} else// 如果当前是从右到左遍历,按右子树左子树的顺序添加
    			{
    				if (node.right != null)
    					nextStack.add(node.right);
    				if (node.left != null)
    					nextStack.add(node.left);
    			}
    			if (stack.isEmpty()) {
    				// 交换两个栈
    				Stack<TreeNode> tmp = stack;
    				stack = nextStack;
    				nextStack = tmp;
    				// 标记下一层处理的方向
    				flag = 1 - flag;
    				ans.add(new ArrayList<>(lay));
    				lay.clear();
    			}
    		}
    		return ans;
    
    	}
  • 相关阅读:
    数组练习
    数组
    表达式和语句
    搜索框制作
    操作DOM
    数据类型
    javascript数组属性及方法
    javascript字符串属性及常用方法总结
    css清除浮动float
    vue项目搭建步骤
  • 原文地址:https://www.cnblogs.com/blythe/p/7536026.html
Copyright © 2011-2022 走看看