题目:
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.
题目解答:
这道题借助了之前做的层次遍历的题目的代码,增加了一个判断条件,如果可以确定当前节点是叶子节点,则返回其深度,也就是找到的最近的叶子节点的深度。
代码如下:
/**
* Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution { public: int minDepth(TreeNode* root) { int depth = 0; int curnum = 0; int childnum = 0; if(root == NULL) { return 0; } queue<TreeNode *> TreeQueue; TreeQueue.push(root); curnum = 1; while(curnum != 0) { vector<int> tmp; depth++; while(curnum != 0) { TreeNode *p = TreeQueue.front(); tmp.push_back(p -> val); if((p -> left == NULL) && (p -> right == NULL)) { return depth; } if(p -> left != NULL) { TreeQueue.push(p -> left); childnum++; } if(p -> right != NULL) { TreeQueue.push(p -> right); childnum++; } TreeQueue.pop(); curnum--; } curnum = childnum; childnum = 0; } return depth; }};