Minimum Depth of Binary Tree

Q:

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.

A:

还是采用类似于后序遍历的方式,弹栈的时候判断是否为叶子节点,ok

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
 public:
  int minDepth(TreeNode *root) {
    // Start typing your C/C++ solution below
    // DO NOT write int main() function
    if (!root) return 0; 
    stack<TreeNode*> s;
    stack<bool> r;
    int l = 0x0ffffffe;
    int cur_h = 0;
    TreeNode* cur = root;
    while (cur || !s.empty()) {
      while (cur) {
        s.push(cur);
        r.push(false);
        ++cur_h;
        cur = cur->left;
      }   
      while (!r.empty() && r.top()) {
        TreeNode* tmp = s.top();
        if (!tmp->left && !tmp->right) {
          l = min(l, cur_h);
        }   
        s.pop();
        r.pop();
        --cur_h;
      }   
        
      if (!s.empty()) {
        cur = s.top()->right;
        r.top() = true;
      }   
    }   
    return l;
  }
};

 

posted @ 2013-06-17 12:34  dmthinker  阅读(115)  评论(0)    收藏  举报