Minimum Depth of Binary Tree leetcode java


題目

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

 

題解

遞歸解法急速判斷左右兩邊子樹哪個depth最小,要注意如果有個節點只有一邊孩子時,不能返回0,要返回另外一半邊的depth。

遞歸解法:

1      public  int minDepth(TreeNode root) {
2          if(root ==  null)
3              return 0;
4          int minleft = minDepth(root.left);
5          int minright = minDepth(root.right);
6          if(minleft==0 || minright==0)
7              return minleft>=minright?minleft+1:minright+1;
8          return Math.min(minleft,minright)+1;
9     }

 非遞歸解法:

 1      public  int minDepth(TreeNode root) {
 2          if(root ==  null)
 3              return 0;
 4         
 5          int depth = 1;//The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
 6         LinkedList<TreeNode> queue =  new LinkedList<TreeNode>();
 7         queue.add(root);
 8          int curnum = 1;
 9          int nextnum = 0;
10          while(!queue.isEmpty()){
11             TreeNode cur = queue.poll();
12             curnum--;
13             
14              if(cur.left ==  null && cur.right ==  null)
15                  return depth;
16             
17              if(cur.left !=  null){
18                queue.add(cur.left);
19                nextnum++;
20             }
21             
22              if(cur.right !=  null){
23                 queue.add(cur.right);
24                 nextnum++;
25             }
26             
27              if(curnum == 0){
28                 curnum = nextnum;
29                 nextnum = 0;
30                 depth++;
31             }
32         }
33          return depth;
34     }

 


免責聲明!

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



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