美文网首页
102. Binary Tree Level Order Tra

102. Binary Tree Level Order Tra

作者: 7ccc099f4608 | 来源:发表于2020-03-15 23:40 被阅读0次

    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;
        }
    
    

    相关文章

      网友评论

          本文标题:102. Binary Tree Level Order Tra

          本文链接:https://www.haomeiwen.com/subject/azwiehtx.html