Minimum Depth of Binary Tree
Description
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.
Example Given a binary tree as follow: 1 / \ 2 3 / \ 4 5 The minimum depth is 2.
Link
Method
- BFS
- x
Example
- 1
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { public: /** * @param root: The root of binary tree. * @return: An integer */ int minDepth(TreeNode *root) { // write your code here if (!root) { return 0; } int count = 1; int depth = 0; queue<TreeNode*> q; q.push(root); while (!q.empty()) { TreeNode* cur = q.front(); q.pop(); count--; // find min shallow leaf node if (!cur->left && !cur->right) { return depth + 1; } // upadte q if (cur->left) { q.push(cur->left); } if (cur->right) { q.push(cur->right); } // update level summary if (count == 0) { count = q.size(); ++depth; } } return -1; } };
Similar problems
x
Tags
x