您的位置:首页 > 其它

[Leetcode 104, Easy] Minimum (Maximum) Depth of Binary Tree

2013-11-07 05:50 429 查看
Problem:

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.
Analysis:

第一种方法是迭代法。在此不熬述了。

第二种是后序遍历。方法在此也不重复了。只需要说明的是:计算path的长度只能用后续遍历。前序和中序都会在右节点不空时,先弹出根节点,这样计算的path长度就会少一。

Solution:

C++:

void getDepth(TreeNode *root, vector<TreeNode *> &curPath, vector<vector<TreeNode *> > &Path){
        
        if(root->left==NULL && root->right==NULL){
            curPath.push_back(root);
            Path.push_back(curPath);
            curPath.erase(curPath.end()-1, curPath.end());
        }else{
            curPath.push_back(root);
            
            if(root->left!=NULL)    getDepth(root->left, curPath, Path);
            
            if(root->right!=NULL)   getDepth(root->right, curPath, Path);
            
            curPath.erase(curPath.end()-1, curPath.end());
        }
    }

    int minDepth(TreeNode *root) {
        vector<vector<TreeNode *> > Path;
        if(root==NULL) return 0;
        
        vector<TreeNode *> curPath(1, root);
        if(root->left==NULL && root->right==NULL) return 1;
        
        if(root->left!=NULL)    getDepth(root->left, curPath, Path);
            
        if(root->right!=NULL)   getDepth(root->right, curPath, Path);
        
        <strong>int minLen=Path[0].size();
        for(int i=1; i<Path.size(); ++i){
            if(minLen>Path[i].size()) minLen=Path[i].size();
        }
        
        return minLen;</strong>
        
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: