[LeetCode-111] Minimum Depth of Binary Tree (二叉树最小深度)

来源:互联网 发布:姆潘巴现象知乎 编辑:程序博客网 时间:2024/06/14 01:58

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)如果二叉树为空,二叉树的深度为0 
(2)如果二叉树不为空,二叉树的深度 = min(左子树深度, 右子树深度) + 1

(3)需要注意的是斜二叉树情况,当节点的左子树深度为0或者节点的右子树深度为0.

采用DFS深度优先遍历,我们只要叶子节点。

/** * Definition for a binary tree node.  */struct TreeNode {int val;struct TreeNode *left;struct TreeNode *right;};int minDepth(TreeNode *root) {   // Start typing your C/C++ solution below   // DO NOT write int main() function   if (root == NULL)   return 0;      if (root->left == NULL && root->right == NULL)   return 1;      int leftDepth = minDepth(root->left);   int rightDepth = minDepth(root->right);      if (leftDepth == 0)   return rightDepth + 1;   else if (rightDepth == 0)   return leftDepth + 1;   else   return leftDepth < rightDepth ? (leftDepth +1 ) : (rightDepth +1); }



1 0
原创粉丝点击