[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.

这道题是让求出一棵二叉树中的最短路径的长度。很显然,它的思路与求树的深度有很大的相似之处。采用减治的方法,将原始问题转换为求根节点的左子树和右子树的最短路径。求左右子树的最短路径时也同样采用上述方式。 有一点需要注意的是,若一个结点只有一个子树,,则为空的那个子树的深度为0,忽略;若一个结点有两个子树,则返回最短路径较小的。 下面贴上代码:

/** * 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;int left = minDepth(root->left);int right = minDepth(root->right);if (left&&right){return (left < right ? left : right) + 1;}else{return left + right + 1;}}};

发光并非太阳的专利,我也可以发光 。

[LeetCode]Minimum Depth of Binary Tree

相关文章:

你感兴趣的文章:

标签云: