1. 程式人生 > >1. minimum-depth-of-binary-tree

1. minimum-depth-of-binary-tree

題目描述

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.

思路:

廣度優先搜尋,BFS。

藉助佇列,將樹中結點按層壓入,迴圈的終止條件是當前結點沒有左右子樹,也就是佇列的長度在壓入當前結點的左右子樹前與壓入後相同。

class Solution {
public:
    int run(TreeNode *root) {
        if(!root)
            return 0;
        queue<TreeNode* > q;
        q.push(root);
        int level = 1, size = 0;
        TreeNode* pNode = root;
        TreeNode* pLast = root;
        while(!q.empty())
        {
            pNode = q.front();
            q.pop();
            size = q.size();
            if(pNode->left)
                q.push(pNode->left);
            if(pNode->right)
                q.push(pNode->right);
            if(size == q.size())
                break;
            if(pNode == pLast)
            {
                ++level;
                pLast = q.back();
            }
        }
        return level;
    }
};

另一種解法:深度優先搜尋,DFS。

深度優先搜尋需要迭代來遍歷所有結點,所以效率比BFS低。

class Solution {
public:
    int run(TreeNode *root) {
        if(!root)
            return 0;
        if(!root->left)
            return run(root->right) + 1;
        if(!root->right)
            return run(root->left) + 1;
        int left = run(root->left);
        int right = run(root->right);
        return 1 + min(left, right);
    }
};