美文网首页
leetcode102.二叉树的层序遍历,103.二叉树的锯齿形

leetcode102.二叉树的层序遍历,103.二叉树的锯齿形

作者: 憨憨二师兄 | 来源:发表于2020-05-12 15:16 被阅读0次

云淡风轻近午天,傍花随柳过前川。
时人不识余心乐,将谓偷闲学少年。

程颢的《春日偶成》,大概意思是忙里偷闲的感觉很爽(上班摸鱼写题感觉确实爽~)

二叉树的层序遍历

题目链接

思路:queue

BFS的思想 (゜- ゜)つ,实在没什么好解释的,过程省略~

代码如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {


    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if(root == null){
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            List<Integer> list = new ArrayList<>();
            for(int i = 0; i < size; ++i){
                root = queue.poll();
                list.add(root.val);
                if(root.left != null){
                    queue.offer(root.left);
                }
                if(root.right != null){
                    queue.offer(root.right);
                }
            }
            res.add(list);
        }
        return res;
    }
}

时间复杂度:
二叉树的每个节点进出队列各一次,所以时间复杂度为O(N)

额外空间复杂度:
额外使用了队列这种数据结构,队列中元素的个数不会超过n个,额外空间复杂度为O(N)

执行结果:

二叉树的锯齿形层次遍历

题目链接

思路:queue

较上一题而言,只需要加入奇偶的判断即可,实在没什么好解释的了,具体可以见代码
代码如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if(root == null){
            return res;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        boolean isLeftToRight = false;
        while(!queue.isEmpty()){
            int size = queue.size();
            List<Integer> list = new ArrayList<>();

            isLeftToRight = !isLeftToRight;

            for(int i = 0; i < size; ++i){
                root = queue.poll();
                if(isLeftToRight){
                    list.add(root.val);
                }else{
                    list.add(0,root.val);
                }
                
                if(root.left != null){
                    queue.offer(root.left);
                }
                if(root.right != null){
                    queue.offer(root.right);
                }
                
            }
            res.add(list);
        }
        return res;
    }

时间复杂度:O(N)
额外空间复杂度:O(N)

执行结果:


相关文章

网友评论

      本文标题:leetcode102.二叉树的层序遍历,103.二叉树的锯齿形

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