[數據結構與算法]求給定二叉樹的最小深度。最小深度是指樹的根結點到最近葉子結點的最短路徑上結點的數量。


解題思路:

剛開始想到的就是利用回溯,樹的最小深度等於樹的左右子樹的最小深度+1;

根據這個想法,寫出解題算法

public class Solution {
    public int run(TreeNode root) {
        TreeNode node = root;
        
//遞歸的邊界條件 如果當前節點為null 高度為0
        if(node == null)
           return 0;
//遞歸的邊界條件 如果當前節點是葉子節點(左右子樹都為null),高度是1
        if(node.left == null && node.right == null){
            return 1;
        }
//否則 左右節點有值 當前節點高度(只看當前節點)為1+ 那個不為null的子樹的高度,因此為max      
        if(node.left == null || node.right == null){
            return 1 + Math.max(run(node.left), run(node.right));
        }
        //最后是都不為空 1+左右子樹的最小高度
        return 1 + Math.min(run(node.left), run(node.right));
    }
}

 另一種非遞歸的方法是層序遍歷,從根節點開始,從上往下,利用一個隊列存放需要遍歷的節點,

代碼:

public int run(TreeNode root) {

        if(root ==null)
            return 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        int depth = 0;//當前樹的深度
        while(!queue.isEmpty()){
            int size = queue.size(); //這個地方是關鍵,獲取當前層需要遍歷的節點個數

            for(int i = 0; i < size; i++){
                TreeNode current = queue.poll();
                if(current.left == null && current.right == null) //如果左右子樹都為空
                    return 1 + depth;
                if(current.left != null){
                    queue.offer(current.left);
                }
                if(current.right != null){
                    queue.offer(current.right);
                }
            }
            depth++;
        }
        return depth;
    }

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM