111. 二叉树的最小深度
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution 11 { 12 public: 13 int minDepth(TreeNode* root) 14 { 15 if(!root) return 0; 16 if(root->left == NULL) return minDepth(root->right) + 1; 17 else if(root->right == NULL) return minDepth(root->left) + 1; 18 else return min(minDepth(root->left),minDepth(root->right)) + 1; 19 } 20 };
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution 11 { 12 public: 13 int minDepth(TreeNode* root) 14 { 15 if (root == NULL) return 0; 16 queue<TreeNode*> q; 17 q.push(root); 18 // root 本身就是一层,depth 初始化为 1 19 int depth = 1; 20 21 while (!q.empty()) 22 { 23 int sz = q.size(); 24 /* 将当前队列中的所有节点向四周扩散 */ 25 for (int i = 0; i < sz; i++) 26 { 27 TreeNode* cur = q.front(); 28 q.pop(); 29 /* 判断是否到达终点 */ 30 if (cur->left == NULL && cur->right == NULL) 31 return depth; 32 /* 将 cur 的相邻节点加入队列 */ 33 if (cur->left) q.push(cur->left); 34 if (cur->right) q.push(cur->right); 35 } 36 /* 这里增加步数 */ 37 depth++; 38 } 39 return depth; 40 } 41 };
Mamba never out

浙公网安备 33010602011771号