求二叉树的层序遍历

求二叉树的层序遍历

http://www.nowcoder.com/questionTerminal/04a5560e43e24e9db4595865dc9c63a3

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */


public class Solution {
    /**
     * @param root TreeNode类
     * @return int整型ArrayList<ArrayList <>>
     */
    public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
        // write code here

        // write code here
        LinkedList<TreeNode> queueFather = new LinkedList<>();
        LinkedList<TreeNode> queueChild = new LinkedList<>();

        ArrayList<ArrayList<Integer>> resultList = new ArrayList<>();
        if (root != null) {
            queueFather.add(root);
        }

        while (queueFather.size() > 0 || queueChild.size() > 0) {
            ArrayList<Integer> rowList = new ArrayList<>();
            if (queueFather.size() > 0) {
                while (queueFather.size() > 0) {
                    TreeNode node = queueFather.pop();
                    if (node.left != null) {
                        queueChild.add(node.left);
                    }
                    if (node.right != null) {
                        queueChild.add(node.right);
                    }
                    rowList.add(node.val);
                }
            } else{
                while (queueChild.size() > 0) {
                    TreeNode node = queueChild.pop();
                    if (node.left != null) {
                        queueFather.add(node.left);
                    }
                    if (node.right != null) {
                        queueFather.add(node.right);
                    }
                    rowList.add(node.val);
                }

            }
            resultList.add(rowList);

        }
        return resultList;
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
11-21 22:29
点赞 评论 收藏
分享
勤奋努力的椰子这就开摆:美团骑手在美团工作没毛病
投递美团等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务