老汉技术专栏

Java开发程序猿一枚~欢迎各位批评指正

LintCode 71. 二叉树的锯齿形层次遍历

给出一棵二叉树,返回其节点值的锯齿形层次遍历(先从左往右,下一层再从右往左,层与层之间交替进行) 

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
   /**
    * @param root: A Tree
    * @return: A list of lists of integer include the zigzag level order traversal of its nodes' values.
    */
   public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
      // write your code here
      List<List<Integer>> list = new ArrayList<>();
      LinkedList<TreeNode> queue = new LinkedList<>();
      if (root != null) {
         queue.offer(root);
      }
      int depth = 1;
      while (!queue.isEmpty()) {
         int len = queue.size();
         List<Integer> tmpList = new ArrayList<>();
         while (len > 0) {
            TreeNode treeNode = queue.poll();
            tmpList.add(treeNode.val);
            if (treeNode.left != null) {
               queue.offer(treeNode.left);
            }
            if (treeNode.right != null) {
               queue.offer(treeNode.right);
            }
            len--;
         }
         if (depth % 2 == 0) {
            Collections.reverse(tmpList);
         }
         depth++;
         list.add(tmpList);
      }
      return list;
   }
}

阅读更多
文章标签: java lintcode
个人分类: java开发
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

LintCode 71. 二叉树的锯齿形层次遍历

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭