剑指38.二叉树的深度

题目描述

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
 

思路

思路1:采用递归实现。树的深度=max(左子树深度,右子树深度)+1。
 
思路2:层序遍历。
 

解法1

/**
 public class TreeNode {
 int val = 0;
 TreeNode left = null;
 TreeNode right = null;

 public TreeNode(int val) {
 this.val = val;

 }

 }
 */
public class Solution {
    public int TreeDepth(TreeNode root) {
        if (root == null)
            return 0;
        // 分别得到root左右孩子的深度
        int left = TreeDepth(root.left);
        int right = TreeDepth(root.right);
        return Math.max(left,right) + 1;
    }
}

 

解法2

import java.util.*;
//BFS的层次遍历思想,记录二叉树的层数,
//遍历完,层数即为最大深度
public class Solution {
    public int TreeDepth(TreeNode root) {
        if(root == null) return 0;
        int depth = 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            int levelNums = queue.size();//先获取本层的节点数,然后遍历
            depth++;
            for(int i = 0; i < levelNums; i++){
                TreeNode cur = queue.poll();
                if(cur.left != null) queue.offer(cur.left);
                if(cur.right != null) queue.offer(cur.right);
            }
        }
        return depth;
    }
}

 

 
posted @ 2020-08-23 15:23  不学无墅_NKer  阅读(188)  评论(0编辑  收藏  举报