欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

剑指offer 二叉树的深度 Java

程序员文章站 2022-07-10 15:31:10
...

递归写法

/**
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;
        }
        int left = TreeDepth(root.left);
        int right = TreeDepth(root.right);
        return Math.max(left,right)+1;
        
    }
}

非递归 BFS实现

import java.util.*;
/**
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;
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        int size,level = 0;
        TreeNode now;
        while(!queue.isEmpty()){
            level++;
            size = queue.size();
            while(size --> 0){
                now = queue.poll();
                if(now.left != null) queue.offer(now.left);
                if(now.right != null) queue.offer(now.right);
            }
        }
        return level;
    }
}