码迷,mamicode.com
首页 > 其他好文 > 详细

Minimum -depth -of -binary -tree@LeetCode

时间:2017-02-26 12:08:35      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:存在   rank   class   binary   tps   minimum   number   cti   使用   

链接:https://www.nowcoder.com/practice/e08819cfdeb34985a8de9c4e6562e724?tpId=46&tqId=29030&tPage=1&rp=1&ru=/ta/leetcode&qru=/ta/leetcode/question-ranking
来源:牛客网

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.

基本思想:

  叶子节点:度0的结点,没有孩子。

  二叉树的最小深度,不同于二叉树的最大深度,不能够单纯使用递归,方式比较所有的叶子节点同时记录所有的到根节点的深度,最后进行比较。

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public int run(TreeNode root) {
12         if (root==null) return 0;
13         /*使用递归判断此节点是否是叶子节点*/
14         if(root.left==null && root.right==null) return 1;
15            /*二叉树左子树空,叶子节点在右子树上*/
16         if(root.left==null)
17             return run(root.right)+1;
18         if(root.right==null)
19             return 1+run(root.left);
20         /*左右儿子,比较得到其中最小值*/
21         return Math.min(run(root.left),run(root.right))+1;
22     }
23 }

 C++语言更加的简洁,求最大深度树,将最后11行代码修改成   max(L,R)+1;

 1 class Solution {
 2 public:
 3     int run(TreeNode *root) {
 4         if(root==NULL)
 5             return 0;
 6         int L=run(root->left);
 7         int R=run(root->right);
 8         
 9         if(L==0 || R==0)
10             return 1+L+R;/*此节点不存在,父节点最多只有一个儿子,计算出叶子叶子节点到此结点的深度,要么只有一个节点,要么根节点*/
11         return (L<R?L:R)+1;
12           
13     }
14 };

 

Minimum -depth -of -binary -tree@LeetCode

标签:存在   rank   class   binary   tps   minimum   number   cti   使用   

原文地址:http://www.cnblogs.com/woainifanfan/p/6443810.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!