leetcode:Minimum Depth of Binary Tree
/**
* 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 depth=0; vector<TreeNode*>vec; vec.push_back(root); TreeNode *p; int cur=0; int last=1; while(cur<vec.size()) { p=vec[cur]; if(cur==last) { ++depth; last=vec.size(); } ++cur; if(!p->left&&!p->right) { break; } if(p->left) vec.push_back(p->left); if(p->right) vec.push_back(p->right); } ++depth; return depth; } };

浙公网安备 33010602011771号