c_cpp [tree] [dfs] [bfs]二叉树的最小深度

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp [tree] [dfs] [bfs]二叉树的最小深度相关的知识,希望对你有一定的参考价值。

// solution 1, recursive

int minDepth(TreeNode *root) {
    if(!root) return 0;
    if(!root->left && !root->right) return 1;
    int minHL = minDepth(root->left), minHR = minDepth(root->right);
    if(!root->left && root->right) return 1+minHR;
    if(root->left && !root->right) return 1+minHL;
    return 1 + min(minHR, minHL);
} 

// solution 2, iterative version 

int minDepth(TreeNode *root) {
    if(!root) return 0;
    if(!root->left && !root->right) return 1;
    queue<TreeNode*> q;
    q.push(root);
    int min_depth = 1, level1 = 1, level2 = 0;
    while(!q.empty()) {
        TreeNode *cur = q.front();
        q.pop();
        level1--;
        // if(!cur) continue; // wrong!! cannot write like this. otherwise, POS1 cannot be executed.
        if(cur) {
            if(!cur->left && !cur->right) return min_depth;
            q.push(cur->left);
            q.push(cur->right);
            level2 += 2;
        }
        if(level1 == 0) { // POS1
            level1 = level2;
            min_depth++;
            level2 = 0;
        }
    }
    return min_depth;
}

// a better iterative version

int minDepth(TreeNode *root) {
    if(!root) return 0;
    if(!root->left && !root->right) return 1;
    queue<TreeNode*> q;
    q.push(root);
    int min_depth = 1, level1 = 1, level2 = 0;
    while(!q.empty()) {
        TreeNode *cur = q.front();
        q.pop();
        level1--;

        if(!cur->left && !cur->right) return min_depth;
        
        if(cur->left) { q.push(cur->left); level2++; }
        if(cur->right) { q.push(cur->right); level2++; }

        if(level1 == 0) {
            level1 = level2;
            min_depth++;
            level2 = 0;
        }
    }
    return min_depth;
}

以上是关于c_cpp [tree] [dfs] [bfs]二叉树的最小深度的主要内容,如果未能解决你的问题,请参考以下文章

UVA - 10410 Tree Reconstruction (根据dfs序和bfs序恢复一颗树)

Leetcode-dfs & bfs

leetcode 261-Graph Valid Tree(medium)(BFS, DFS, Union find)

LeetCode 0623.在二叉树中增加一行:DFS / BFS

UVA - 10410 Tree Reconstruction(栈处理递归)

CF570D:Tree Requests