1. 程式人生 > >LeetCode之二叉樹最小深度(簡單 二叉樹)

LeetCode之二叉樹最小深度(簡單 二叉樹)

給定一個二叉樹,找出其最小深度。

最小深度是從根節點到最近葉子節點的最短路徑上的節點數量。

說明: 葉子節點是指沒有子節點的節點。

示例:

給定二叉樹 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回它的最小深度  2.

一層一層遍歷,每遍歷一層,高度+1,知道遇到葉節點,返回高度。

public int minDepth(TreeNode root) {
        if(root == null){
            return 0;
        }
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        int depth = 0;
        while(!q.isEmpty()){
            int size = q.size();
            depth ++;
            for (int i = 0; i < size; i++) {
                TreeNode t = q.poll();
                if(t.left==null&&t.right==null){
                    return depth;
                }
                if(t.left!=null){
                    q.offer(t.left);
                }
                if(t.right!=null){
                    q.offer(t.right);
                }
            }
        }
        return depth;
    }

我一般寫非遞迴之前總會想一想遞迴演算法,但是總是想不完整,我發現這些大神總是能想出遞迴,只要寫幾行程式碼就結束了,氣啊,最氣的是自己寫非遞迴幾十行,執行時間還沒人家幾行的快,百思不得其解,推測大概是測試資料二叉樹的深度不高導致遞迴的次數不多程式碼少,自然節約時間。氣氣氣,大神程式碼走起

public int minDepth(TreeNode root) {
          if (root==null) return 0;
        if (root.left==null &&root.right==null)
            return 1;
        else if (root.left!=null &&root.right !=null)
            return (Math.min (minDepth (root.left), minDepth(root.right)) +1);
        else if (root.left==null)
            return minDepth (root.right)+1;
        else 
            return minDepth (root.left) +1;
    }

基本啥都能給你弄成遞迴,厲害厲害。