美文网首页
2019-09-23 算法学习笔记一

2019-09-23 算法学习笔记一

作者: constantine丶 | 来源:发表于2019-10-15 15:34 被阅读0次

1.LeetCode 对应习题

1.102 二叉树的层次遍历
(1)BFS 广度优先搜索
a.level => queue
b.Batch proccess: 代码 √
时间复杂度 o(N)
(2)DFS 深度优先搜索
DFS:(level) 纪录节点的深度 存入二维数组里面
时间复杂度 o(N)

class Solution {
    List<List<Integer>> levels = new ArrayList<List<Integer>>();

    public void helper(TreeNode node, int level) {
        // start the current level
        if (levels.size() == level)
            levels.add(new ArrayList<Integer>());

         // fulfil the current level
         levels.get(level).add(node.val);

         // process child nodes for the next level
         if (node.left != null)
            helper(node.left, level + 1);
         if (node.right != null)
            helper(node.right, level + 1);
    }
    
    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) return levels;
        helper(root, 0);
        return levels;
    }
}

2.104 111 二叉树的层次遍历

相关文章

网友评论

      本文标题:2019-09-23 算法学习笔记一

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