102. Binary Tree Level Order Tra

2020-03-15  本文已影响0人  7ccc099f4608

https://leetcode-cn.com/problems/binary-tree-level-order-traversal/

image.png

(图片来源[https://leetcode-cn.com/problems/binary-tree-level-order-traversal/

日期 是否一次通过 comment
2020-03-15 0

递归

public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if(root == null) {
            return res;
        }

        helper(root, res, 0);
        return res;
    }

    private void helper(TreeNode root, List<List<Integer>> res, int level) {
        if(root == null) {
            return;
        }

        if(level >= res.size()) {
            res.add(new ArrayList<>());
        }

        res.get(level).add(root.val);

        helper(root.left, res, level+1);
        helper(root.right, res, level+1);

    }

非递归

public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();

        if(root == null) {
            return result;
        }

        Queue<TreeNode> nodeQ = new LinkedList<>();
        nodeQ.offer(root);
        while(! nodeQ.isEmpty()) {
            int qLen = nodeQ.size();
            List<Integer> tempList = new ArrayList<>();

            for(int i=0; i<qLen; i++) {
                TreeNode tempNode = nodeQ.poll();
                tempList.add(tempNode.val);
                if(tempNode.left != null) {
                    nodeQ.offer(tempNode.left);
                }

                if(tempNode.right != null) {
                    nodeQ.offer(tempNode.right);
                }

            }

            result.add(tempList);
        }

        return result;
    }

上一篇下一篇

猜你喜欢

热点阅读