LeetCode 111 Minimum Depth of Binary Tree(DFS)

来源:互联网 发布:诺基亚500软件 编辑:程序博客网 时间:2024/05/22 15: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.

题目大意:给出一个二叉树,求从根节点到叶节点的最小深度。

解题思路:直接DFS,和LeetCode 104 Maximum Depth of Bianry Tree类似,只不过多了些判断。

代码如下:

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     struct TreeNode *left; *     struct TreeNode *right; * }; */int minDepth(struct TreeNode* root) {    if(root == NULL) return 0;    else if(root->left && !root->right) return 1 + minDepth(root->left);    else if(root->right && !root->left) return 1 + minDepth(root->right);    else{        int left = 1 + minDepth(root->left);        int right = 1 + minDepth(root->right);        return left < right ? left : right;    }}

原创粉丝点击