码迷,mamicode.com
首页 > 其他好文 > 详细

39.2: Binary Tree Zigzag Level Order Traversal

时间:2015-01-27 23:17:40      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

 /************************************************************************/
        /*       38:      Binary Tree Zigzag Level Order Traversal                                       */
        /************************************************************************/
        /*
         * 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,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

return its zigzag level order traversal as:

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

         * */
        
        /*** 树的按照层遍历 ,类似 BFS***********************************************************/

public List<List<Integer>> zigzagLevelOrder(TreeNode root) 
        {
             List<List<Integer>> result = new ArrayList<>();
                List<TreeNode> level = new ArrayList<>();
                level.add(root);
                boolean leftflag=true;
                while(true){
                    if (level.isEmpty() || level.get(0) == null){
                        break;
                    }
                    List<TreeNode> nextLevel = new ArrayList<>();
                    List<Integer> currentLevel = new ArrayList<>();
                    
                    if(leftflag) //left to right
                    {
                         for (TreeNode node : level){
                                currentLevel.add(node.val);
                                if (node.left != null) nextLevel.add(node.left);
                                if (node.right != null) nextLevel.add(node.right);
                            }
                    }
                    else
                    {
                        for(int i=level.size()-1;i>=0;i--)
                        {
                            currentLevel.add(level.get(i).val);
                            if (level.get(level.size()-1-i).left != null) nextLevel.add(level.get(level.size()-1-i).left);
                            if (level.get(level.size()-1-i).right != null) nextLevel.add(level.get(level.size()-1-i).right);
                        }
                    }
                    result.add(currentLevel);
                    level = nextLevel;
                    leftflag=!leftflag;
                }
                return result;
            
        }

 

39.2: Binary Tree Zigzag Level Order Traversal

标签:

原文地址:http://www.cnblogs.com/theonemars/p/4254207.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!