剑指OFFER-二叉树的深度(Java)

题目描述

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

核心代码实现

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

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

    }

}
*/
import java.util.*;

public class Solution {
    
    
    public int TreeDepth(TreeNode root) {
    
    
        if(root == null){
    
    
            return 0;
        }
        /**递归
        int leftDepth = TreeDepth(root.left);
        int rightDepth = TreeDepth(root.right);
        int DepthOfTree = ((leftDepth > rightDepth)? leftDepth : rightDepth) + 1;
        return DepthOfTree;
        */
        
        //层次遍历,二叉树的层数即为其最大深度
        LinkedList<TreeNode> list = new LinkedList<TreeNode>();
        list.add(root);
        int DepthOfTree = 0;
        while(!list.isEmpty()){
    
    
            DepthOfTree = DepthOfTree + 1;
            int size = list.size();    //记录当前层次的节点数
            for(int i = 0; i < size; i++){
    
    
                TreeNode node = list.poll();    //遍历当前层次的节点
                if(node.left != null){
    
    
                    list.add(node.left);
                }
                if(node.right != null){
    
    
                    list.add(node.right);
                }
            }
        }
        return DepthOfTree;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_48440312/article/details/109305265