Minimum Depth of Binary Tree-求二叉樹的最小深度

  • 求二叉樹的最小深度,是常見的一種二叉樹算法問題,主要解決辦法有兩種,一種是使用遞歸求解,另外一種是非遞歸方式求解。這裏給出遞歸求解方法。遞歸方法須要判斷左右子樹是否爲空,當左子樹爲空,返回右子樹的的最小深度+1,當右子樹爲空,返回左子樹的最小深度+1,當左右子樹均不爲空時,返回左子樹與右子樹最小深度+1。
  • 問題來源於leetcode:https://leetcode.com/problems/minimum-depth-of-binary-tree/description/
  • Java遞歸求解方法:
 1 /**
 2  * Definition for a binary tree node.
 3   */
 4   public class TreeNode {
 5      int val;
 6      TreeNode left;
 7      TreeNode right;
 8      TreeNode(int x) { val = x; }
 9  }
10 
11 class Solution {
12     public int minDepth(TreeNode root) {
13         if(null == root){
14             return 0;
15         }
16         if(root.left == null){
17             return minDepth(root.right)+1;
18         }
19         if(root.right == null){
20             return minDepth(root.left)+1;
21         }
22         return  Math.min(minDepth(root.left), minDepth(root.right))+1;
23         
24     }
25 }
相關文章
相關標籤/搜索