111. 二叉树的最小深度
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
Solution1(递归版):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Solution { public: int minDepth(TreeNode* root) { if(!root) return 0; return depth(root); } int depth(TreeNode* root){ if(!root->left && !root->right) return 1; int l = INT_MAX, r = INT_MAX; if(root->left){ l = 1 + depth(root->left); }if(root->right){ r = 1 + depth(root->right); } return min(l,r); } };
|
递归到叶子节点就停止。
如果不是叶子结点。则向下递归,找到最小值即可。
Solution2(迭代版):
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
| class Solution { public: int minDepth(TreeNode* root) { if(!root) return 0; queue<TreeNode*> q; q.push(root); int depth = 0; while(!q.empty()){ int len = q.size(); depth++; while(len > 0){ TreeNode* t = q.front(); q.pop(); if(!t->left && !t->right) { return depth; } if(t->left)q.push(t->left); if(t->right)q.push(t->right); len--; } } return depth; } };
|
层次遍历二叉树,每次弹出一层,如果该层有叶子节点,直接返回当前记录的深度。