Live2D

二叉树的深度(java)

//输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
//第一种方法利用先序遍历 获得所有路径的长度 然后取最长的
import java.util.*;
public class Solution {
    ArrayList<Integer> array = new ArrayList<>();
    int i = 0;
    public int TreeDepth(TreeNode root) {
        if(root == null){
            return 0;
        }
        ArrayList<Integer> list = allRoad(root);
        int max = Integer.MIN_VALUE;
        int a ;
        for(int i = 0;i<list.size();i++){
            if(list.get(i)>max){
                max = list.get(i);
            }
        }
        return max;
    }
    
    public ArrayList<Integer> allRoad(TreeNode root){
        if(root == null) return array;
        i++;
        if(root.left==null&&root.right==null){
            array.add(i);//路径到底  将该路径的长度存入arraylist
        }
        allRoad(root.left);
        allRoad(root.right);
        i--;//到头之后需要回退
        return array;
    }
}
import java.util.*;
public class Solution {
    
    public int TreeDepth(TreeNode root) {
        //第二种方法更简单:利用层次遍历
        Queue<TreeNode> q = new LinkedList<>();
        if(root == null){
            return 0;
        }
        q.offer(root);
        int level = 0;
        while(!q.isEmpty()){
            int size = q.size();
            while(size!=0){
                TreeNode node = q.poll();
                if(node.left!=null){
                    q.offer(node.left);
                }
                if(node.right!=null){
                    q.offer(node.right);
                }
                size--;
            }
            level++;
        }
        return level;
    }
}
public class Solution {
    //递归法 代码量最少
    public int TreeDepth(TreeNode root) {
        if(root == null){
            return 0;
        }
        int left = TreeDepth(root.left);
        int right = TreeDepth(root.right);
        return left > right ? left+1 : right+1;
        //return Math.max(TreeDepth(root.left),TreeDepth(root.right))+1;
    }
}
posted @ 2021-01-24 15:54  细雪之舞0213  阅读(144)  评论(0)    收藏  举报