题目:
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.
Anwser 1 :递归的方法 DFS思路:分别计算根结点的左子树和右子树的最短depth,然后判断,如果左右子树都非空,则返回较小的depth。如果左/右子树有一个为空,则返回右/左的最小depth.
Attention:
1. 题目要求一定是根结点到最近叶结点的depth,一定要遍历到叶结点。 所以和Maximum Depth of Binary Tree递归方式不一样。需要判断左右子树是否为空。
2. if(root == NULL) return 0; 是递归介绍的条件,一定不能忘记。
AC Code:
/**
* 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 leftDepth = minDepth(root->left);
int rightDepth = minDepth(root->right);
if(leftDepth != 0 && rightDepth != 0) return min(leftDepth, rightDepth) + 1;
else if(rightDepth == 0) return leftDepth + 1; //如果没有右子树
else if(leftDepth == 0) return rightDepth + 1; //如果没有左子树
}
};
Anwser 1 :非递归的方法 BFS IN queue
思路:level-order traversal and record current level depth, when meet a node which both child is null then return, no need to go farther。
Attention: 初始深度若根结点非空,为1 注意和Maximum Depth of Binary Tree构造的区别,算法不一样。
AC Code:
/**
* 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;
queue<TreeNode*> Current;
Current.push(root);
queue<TreeNode*> Next;
//初始深度若根结点非空,为1 注意和Maximum Depth of Binary Tree构造的区别,算法不一样。
int depth = 1;
while(!Current.empty())
{
while(!Current.empty())
{
TreeNode* node = Current.front();
Current.pop();
if(node->left == NULL && node->right == NULL) return depth;
if(node->left) Next.push(node->left);
if(node->right) Next.push(node->right);
}
queue<TreeNode*> t; //初始化Next,并将Next赋给Current.总是保存当前这一层节点。
Current = Next;
Next = t;
depth++;
}
return depth;
}
};