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;
    
    	}
  • 相关阅读:
    div+css简写原则
    并发控制
    div+css之块级元素与内联元素
    window.event对象属性(转)
    SQL SERVER 架构管理
    关系的规范化
    js常用事件
    物联小白CoAP协议
    图片不停的横滚
    DropDownlist编程问题
  • 原文地址:https://www.cnblogs.com/blythe/p/7536026.html
Copyright © 2011-2022 走看看