N1-1

题目描述:

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.

特殊输入:

只有两个节点时,树的深度是2。但是如果只考虑左子树或右子树为空。结果会返回1.

两个错误的代码:(不应该以子树空判断结束)

实现1:该代码是错误的
class Solution { public: int run(TreeNode *root) { if(root==nullptr) return 0; queue<TreeNode *> currQueue; currQueue.push(root); int count = 0; while(!currQueue.empty()){ count++; for(int i=0;i<currQueue.size();i++){ //遍历一层 TreeNode * pNode = currQueue.front(); currQueue.pop(); if(pNode->left) currQueue.push(pNode->left); else return count; if(pNode->right) currQueue.push(pNode->right); else return count; } } return count; } }
//实现2:  该代码是错误的    
int getMinDepth(TreeNode *root){ if(root==nullptr) return 0; return min(getMinDepth(root->left),getMinDepth(root->right))+1; }

解题思路:

1)一直访问到叶子节点,层次遍历遇到的最早的叶子节点,当前层就是树的最小深度。(使用队列,非递归)

   1
  / 
 2   3
/
4
错误的方法是:当子树为空,返回当前层(上面的例子可以)
但是下面的例子会返回1。
   1
  / 
 2   
class Solution {
public:
    int run(TreeNode *root) {
        if(root==nullptr)
            return 0;
        
        queue<TreeNode *> currQueue;
        currQueue.push(root);
        int count = 0;
        while(!currQueue.empty()){
            count++;
            int size = currQueue.size();
            for(int i=0;i<size;i++){ //遍历一层
                TreeNode * pNode = currQueue.front();
                currQueue.pop();
                if(pNode->left==nullptr && pNode->right==nullptr)  //遇到的第一个叶子节点,返回当前层
                    return count;
                if(pNode->left)
                    currQueue.push(pNode->left);
                if(pNode->right)
                    currQueue.push(pNode->right);
            }
        }
        return count;
    }

};

2)思路:递归

若为空树返回0;
若左子树为空,则返回右子树的最小深度+1;(加1是因为要加上根这一层,下同)
若右子树为空,则返回左子树的最小深度+1;
若左右子树均不为空,则取左、右子树最小深度的较小值,+1;
//实现1
class Solution { public: int run(TreeNode *root) { if(root == nullptr) return 0; if(root->left == nullptr) // 若左子树为空,则返回右子树的最小深度+1 { return run(root->right)+1; } if(root->right == nullptr) // 若右子树为空,则返回左子树的最小深度+1 { return run(root->left)+1; } // 左右子树都不为空时,取较小值 int leftDepth = run(root->left); int rightDepth = run(root->right); return (leftDepth<rightDepth)?(leftDepth+1):(rightDepth+1); } };
//实现2
class Solution {
public:
    int run(TreeNode *root) {
        if(!root)
            return 0;
        int l = run(root->left);
        int r = run(root->right);
        if(l==0 || r==0)
            return 1+l+r;
        return 1+min(l,r);
    }
};

3)深度遍历要遍历所有节点,因此选广度优先遍历更好。不再给出深度遍历的代码  

总结:

二叉树操作主要还是利用尾递归或者循环遍历这两种思路,进而涉及DFS(主要利用递归或者实现)或者BFS(主要利用队列实现)。  

原文地址:https://www.cnblogs.com/GuoXinxin/p/10518146.html