Try   HackMD

【LeetCode】 111. Minimum Depth of Binary Tree

Description

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.

Note: A leaf is a node with no children.

給一棵二元樹,找到它最小深度。

最小深度是指它的離樹根最近的樹葉和樹根的距離。

提示:一個樹葉是指一個節點它沒有小孩。

Example:

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
return its minimum depth = 2.

Solution

  • 使用BFS去遍歷每個節點,除了點之外也需要在queue中存下深度資料。
    • 你也可以使用structpair<>去把資料綁在一起。
  • 將遞迴function中的參數改為指標或參考可以節省空間並加快速度。

Code

/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int BFS(vector<TreeNode*>& queue, vector<int>& q_depth) { TreeNode* node = queue[0]; queue.erase(queue.begin()); int depth = q_depth[0]; q_depth.erase(q_depth.begin()); if(!node) return BFS(queue,q_depth); if(!node->left && !node->right) return depth; if(node->left) { queue.push_back(node->left); q_depth.push_back(depth+1); } if(node->right) { queue.push_back(node->right); q_depth.push_back(depth+1); } while(!queue.empty()) { return BFS(queue,q_depth); } return -1; } int minDepth(TreeNode* root) { if(!root) return 0; vector<TreeNode*> queue(1,root); vector<int> q_depth(1,1); return BFS(queue,q_depth); } };
tags: LeetCode C++