Chinaunix首页 | 论坛 | 博客

AAA

  • 博客访问: 18398
  • 博文数量: 33
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 330
  • 用 户 组: 普通用户
  • 注册时间: 2015-04-17 08:23
个人简介

好记性不如烂笔头,记录学习历程和随想云云,欢迎各位大虾拍砖

文章分类

全部博文(33)

文章存档

2015年(33)

我的朋友
最近访客

分类: C/C++

2015-05-07 23:23:37

【问题描述】

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.


【解决方案】

点击(此处)折叠或打开

  1. /**
  2.  * Definition for binary tree
  3.  * struct TreeNode {
  4.  * int val;
  5.  * struct TreeNode *left;
  6.  * struct TreeNode *right;
  7.   * };
  8.  */
  9. static int min(int a, int b)
  10. {
  11.     if(a<=b)
  12.     {
  13.         return a;
  14.     }
  15.     else
  16.     {
  17.         return b;
  18.     }
  19. }

  20. static int minDepthDfs(struct TreeNode *root, bool hasbrother)
  21. {
  22.     if (!root)
  23.     {
  24.         return hasbrother ? INT_MAX : 0;
  25.     }
  26.     
  27.     return 1 + min(minDepthDfs(root->left, root->right != NULL),
  28.         minDepthDfs(root->right, root->left != NULL));
  29. }

  30. int minDepth(struct TreeNode *root) {
  31.     return minDepthDfs(root, false);
  32. }

阅读(258) | 评论(0) | 转发(0) |
0

上一篇:Number of 1 Bits

下一篇:Path Sum

给主人留下些什么吧!~~