zoukankan      html  css  js  c++  java
  • Binary Tree Zigzag Level Order Traversal,z字形遍历二叉树,得到每层访问的节点值。

    问题描述:

    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]
    ]
    

    算法分析:和前面问题类似。

    public class BinaryTreeZigzagLevelOrderTraversal 
    {
    	 public List<List<Integer>> zigzagLevelOrder(TreeNode root) 
    	 {
    		 List<Integer> list = new ArrayList<>();
    		 List<List<Integer>> res = new ArrayList<>();
    		 
    		 if(root == null) 
    		 {
    			 return res;
    		 }
    		 
    		 Stack<TreeNode> s1 = new Stack<>();
    		 Stack<TreeNode> s2 = new Stack<>();
    		 
    		 s1.push(root);
    		 while(!s1.isEmpty() || !s2.isEmpty())
    		 {
    			 while(!s1.isEmpty())
    			 {
    				 TreeNode temp = s1.pop();
    				 if(temp.left != null)
    				 {
    					 s2.push(temp.left);
    				 }
    				 if(temp.right != null)
    				 {
    					 s2.push(temp.right);
    				 }
    				 list.add(temp.val);
    			 }
    			 if(list.size() != 0)
    				 res.add(list);
    			 list = new ArrayList<>();
    			 while(!s2.isEmpty())
    			 {
    				 TreeNode temp = s2.pop();
    				 if(temp.right != null)
    				 {
    					 s1.push(temp.right);
    				 }
    				 if(temp.left != null)
    				 {
    					 s1.push(temp.left);
    				 }
    				 list.add(temp.val);
    			 }
    			 if(list.size() != 0)
    				 res.add(list);
    			 list = new ArrayList<>();
    		 }
    		 return res;
    	 }
    }
    

      

  • 相关阅读:
    常用不等式例题整理
    洛谷P1233 木棍加工题解 LIS
    莫比乌斯反演
    CSS样式使用
    相邻元素的层级(仿淘宝页面效果)
    js基础知识梳理(最简版)
    css2基础知识梳理
    html4基础知识梳理
    mysql密码遗忘和登陆报错问题
    mysql修改密码过期时间以及密码复杂性问题
  • 原文地址:https://www.cnblogs.com/masterlibin/p/5910492.html
Copyright © 2011-2022 走看看