二叉樹的最小深度

  • minimum depth of binary treenode

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.測試

  • 題目大意:給定一顆二叉樹,找到它的最小深度。最小深度指的是,從根節點到最近的葉子節點,沿着這條路徑走過的節點的數目。rest

  • 思路:利用隊列採用層序遍歷,一旦找到一個葉節點,它確定是最短的。code

  • 代碼:blog

class Solution
{
    public:
        typedef TreeNode* tree;
        int run(TreeNode *root)
        {
            // 層序遍歷,一旦找到一個葉節點,它確定是最短的
            if (root == NULL)return 0;
            queue<tree> qu;
            tree now = root; // 記錄該層的當前節點
            tree last = root; // 記錄該層的最後一個節點
            int level = 1;
            int size = 0;
            qu.push(root);
            while (!qu.empty())
            {
                now = qu.front(); // 取隊首
                qu.pop(); // 出隊首
                size = qu.size();
                if (now->left != NULL)qu.push(now->left);
                if (now->right != NULL)qu.push(now->right);
                // 沒有元素進隊,說明這是一個葉子節點,找到的第一個葉子節點爲最短的
                if (size - qu.size() == 0)break;
                // last==now,說明當前節點走到了該層的最後一個節點
                if (last == now)
                {
                    level++;
                    // last指向下一層的最後一個節點
                    if (!qu.empty())last = qu.back();
                }
            }
            return level;
        }
};
  • 測試結果:隊列

相關文章
相關標籤/搜索