当前位置: 代码迷 >> 综合 >> Leetcode----minmum-depth-of-binary-tree
  详细解决方案

Leetcode----minmum-depth-of-binary-tree

热度:26   发布时间:2024-01-04 02:09:06.0
//minmum-depth-of-binary-tree
//递归深度优先
class Solution {
public:int run(TreeNode *root) {if(root == NULL)return 0;int l  = run(root->left);int r = run(root->right);if(l == 0 || r == 0)//有斜树的情况,即根节点的只有左子树有节点return 1 + r + l;return min(l,r) + 1;}
};
//非递归,层次遍历
class Solution {
public:int run(TreeNode *root) {if(root == NULL)return 0;if(root->left == NULL && root->right == NULL)return 1;queue<TreeNode*> qu;TreeNode * t = NULL;int count = 1;qu.push(root);qu.push(NULL);// 每一层入队后以NULL节点标记下while(!qu.empty()){t = qu.front();qu.pop();if(t == NULL){qu.push(NULL);count++;continue;}if(t->left == NULL && t->right == NULL)return count;if(t->left != NULL)qu.push(t->left);if(t->right!= NULL)qu.push(t->right);}return count;}
};

  相关解决方案