开局之前

二叉树可以使用二分的思想来查询,虽然跳表也可以但是跳表占用的空间大

思考

https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/submissions/

image.png

  1. 可以使用递归来做

    1. class Solution {
    2. public int maxDepth(TreeNode root) {
    3. if(root==null){
    4. return 0;
    5. }
    6. return Math.max(maxDepth(root.left), maxDepth(root.right) )+1;
    7. }
    8. }
  2. 使用层序遍历 一层一层的遍历

    1. public int maxDepth(TreeNode root) {
    2. if(root==null){
    3. return 0;
    4. }
    5. Queue<TreeNode> queue = new LinkedList();
    6. queue.add(root);
    7. int res = 0;
    8. while(!queue.isEmpty()){
    9. int tmpLength = queue.size();
    10. List<Integer> list = new ArrayList();
    11. //内层循环把这层的元素都取出来
    12. for(int i = 0;i<tmpLength;i++){
    13. TreeNode node = queue.poll();
    14. list.add(node.val);
    15. if(node.left!=null){
    16. queue.add(node.left);
    17. }
    18. if(node.right!=null){
    19. queue.add(node.right);
    20. }
    21. }
    22. res++;
    23. }
    24. return res;
    25. }