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++实现代码:
#include<iostream> #include<new> #include<vector> using namespace std; //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) { if(root->left==NULL&&root->right==NULL) return 1; int lmin=minDepth(root->left); int rmin=minDepth(root->right); if(root->left&&root->right==NULL) return lmin+1; if(root->left==NULL&&root->right) return rmin+1; return (lmin<= rmin)?(lmin+1):(rmin+1); } return 0; } void createTree(TreeNode *&root) { int i; cin>>i; if(i!=0) { root=new TreeNode(i); if(root==NULL) return; createTree(root->left); createTree(root->right); } } }; int main() { Solution s; TreeNode *root; s.createTree(root); cout<<s.minDepth(root)<<endl; }