本文主要是介绍Leetcode: Minimum Depth of Binary Tree,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
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.
思路分析:
求二叉树的最小深度。二叉树多用迭代。
C++示例代码:
/*** Definition for binary tree* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/
class Solution
{
public:int minDepth(TreeNode *root){if (root == NULL){return 0;}//leftDepth=0,rightDepth=0直接返回1if (root->left == NULL && root->right == NULL){return 1;}int leftDepth = minDepth(root->left);int rightDepth = minDepth(root->right);//这里leftDepth和rightDepth不可能同时为0if (leftDepth == 0){return rightDepth + 1;}else if (rightDepth == 0){return leftDepth + 1;}else{return min(leftDepth, rightDepth) + 1;}}
};
这篇关于Leetcode: Minimum Depth of Binary Tree的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!