本文共 1372 字,大约阅读时间需要 4 分钟。
struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution { //find the minimum step of a tree, bfs works at most timepublic: int BFS(TreeNode* root) { if(!root) return 0; queue> q; q.push(make_pair(root, 1)); while(!q.empty()) { TreeNode* curNode = q.front().first; int curStep = q.front().second; q.pop();//note here if(!curNode->left && !curNode->right) return curStep; if(curNode->left) q.push(make_pair(curNode->left, curStep+1)); if(curNode->right) q.push(make_pair(curNode->right, curStep+1)); } } int minDepth(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function return BFS(root); }};
second time
/** * 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) { // Start typing your C/C++ solution below // DO NOT write int main() function if(root == NULL) return 0; if(root->left == NULL) return minDepth(root->right)+1; else if(root->right == NULL) return minDepth(root->left)+1; else return min(minDepth(root->left), minDepth(root->right))+1; }};
转载地址:http://rlxti.baihongyu.com/