31、二叉树的最大深度

版权声明:版权所有 https://blog.csdn.net/qq_42253147/article/details/86488076

题目

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

思路

  • 遍历每一层的节点数,然后确定是否还有下一层,然后遍历一层增加length,最后如果没有节点,才是最长的二叉树深度。

代码

import java.util.Queue;
import java.util.LinkedList;
/**
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) {
        Queue<TreeNode> queue = new LinkedList<>();
        int length = 0;
        if(root==null)
            return 0;
        queue.add(root);
        while(queue.size()!=0){
            length++;
            for(int i=0;i<queue.size();i++){
                TreeNode temp = queue.poll();
                if(temp.right!=null)
                    queue.add(temp.right);
                if(temp.left!=null)
                    queue.add(temp.left);
            }
        }
        return length;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42253147/article/details/86488076