zoukankan      html  css  js  c++  java
  • [LeetCode] 103. Binary Tree Zigzag Level Order Traversal Java

    题目:

    Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

    For example:
    Given binary tree [3,9,20,null,null,15,7],

        3
       / 
      9  20
        /  
       15   7

    return its zigzag level order traversal as:

    [
      [3],
      [20,9],
      [15,7]
    ]

    题意及分析:给出一个横向遍历的二叉树,要求给出 按照Z字形横向遍历的每一层 的点。这道题我们可以用stack来求解,简单来讲就是把每一层添加到一个stack里面,然后遍历输出结果的同时将遍历点的子节点添加到一个新的stack里面(先添加左子节点还是右子节点根据上一层添加的顺序),遍历完之后将新的stack赋值给stack进行下一层的遍历。代码如下

    代码:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> res=new ArrayList<>();
    		 	
    		 TreeNode node=root;
    		 Stack<TreeNode> stack =new Stack<>();
    		 if(node!=null)
    			 stack.push(node);
    		 int leftOrRight=0;		//0为先遍历左子树,1为右子树
    		 while(!stack.isEmpty()){
    			 Stack<TreeNode> nextStack =new Stack<>();
    			 List<Integer> list=new ArrayList<>();
    			 while(!stack.isEmpty()){
    				 TreeNode temp=stack.pop();
    				 list.add(temp.val);
    				 if(leftOrRight==0){
    					 if(temp.left!=null)
    						 nextStack.push(temp.left);
    					 if(temp.right!=null)
    						 nextStack.push(temp.right);
    				 }else{
    					 if(temp.right!=null)
    						 nextStack.push(temp.right);
    					 if(temp.left!=null)
    						 nextStack.push(temp.left);
    				 }
    			 }
    			 if(leftOrRight==0)
    				 leftOrRight=1;
    			 else {
    				leftOrRight=0;
    			}
    			 res.add(new ArrayList<>(list));
    			 //System.out.println(list);
    			 list.clear();
    			 stack=(Stack<TreeNode>) nextStack.clone ();;
    			 nextStack.clear();
    		 }
    		 return res;
        }
    }
    

      

  • 相关阅读:
    多个EditText 监听矛盾的 解决办法 (Overstack)溢出栈
    JZ2440 裸机驱动 第5章 GPIO接口
    从头调试stm32 HID
    嵌入式GPIO接口及操作(二)
    嵌入式GPIO接口及操作(一)
    嵌入式linux网络配置
    嵌入式开发环境搭建之安装交叉编译工具链
    securecrt鼠标右键的配置
    S3C2440上LCD驱动(FrameBuffer)实例开发讲解(一)
    s3c2440串口详解
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7017000.html
Copyright © 2011-2022 走看看