天天看點

求二叉樹的層數(計算二叉樹的高度)

一 、遞歸求解

private int countLevel(TreeNode root){
        if(root == null){
            return 0;
        }
        return Math.max(countLevel(root.left),countLevel(root.right)) + 1;
}

           

二、層次周遊

利用隊列的先進先出性質,儲存每一層的結點數,用for循環,循環次數為每一層隊列的size,每poll完一層,則二叉樹高度加1。

繼續閱讀