Leetcode OJ 102 Binary Tree Level Order Traversal [Medium]

Leetcode OJ 102 Binary Tree Level Order Traversal [Medium]

《剑指offer》第4章-面试题32

题目描述:

Given a binary tree, return the level ordertraversal of its nodes' values. (ie, from left to right, level by level).

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

    3

   / \

  9  20

    /  \

   15   7

return its level order traversal as:

[

  [3],

  [9,20],

  [15,7]

]

题目理解:

一层一层打印二叉树。

测试用例:

功能测试:完全二叉树;普通二叉树;只有左子树的二叉树;只有右子树的二叉树;

特殊输入:二叉树根节点是null

分析:

1.  ;

 

错误解答:

   /**

 * Definition for a binary tree node.

 * public class TreeNode {

 *     int val;

 *     TreeNode left;

 *     TreeNode right;

 *     TreeNode(int x) { val = x; }

 * }

 */

class Solution {

    public List> levelOrder(TreeNode root) {

        List> result = new ArrayList>();

        List buffer = new ArrayList();

        TreeNode current = root;

        List subList = new ArrayList();

        int count=0,countNext=1;

        int levelNum = 0;

        

        while(current!= null || !buffer.isEmpty()){

            if(current!=null){

                subList.add(current.val);

                levelNum += 1;

                buffer.add(current.left);

                buffer.add(current.right);

            }

            else{levelNum += 2;}

            if(levelNum == countNext){

                result.add(new ArrayList(subList));

                subList.clear();

                levelNum = 0;

                countNext *= 2;

            }

            //get next node;

            if(!buffer.isEmpty()){

                current = buffer.get(0);

                buffer.remove(0);

            }

            else{

                current = null;

            }

        }

        return result;

    }

}

 


你可能感兴趣的:(Leetcode)