题目描述:
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/BFS都可以, 但是我觉得大概BFS会快一点, 因为在最坏的情况下DFS需要遍历完所有节点才能知道最短的高度.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
class Solution { public: int minDepth(TreeNode* root) { if(!root) return 0; queue<TreeNode*> BFS; queue<int> depth; BFS.push(root); depth.push(1); while(!BFS.empty()){ TreeNode *p = BFS.front(); int d = depth.front(); if(!p->left && !p->right){ return d; } if(p->left){ BFS.push(p->left); depth.push(d + 1); } if(p->right){ BFS.push(p->right); depth.push(d + 1); } BFS.pop(); depth.pop(); } } };
|