leetcode刷题记录---求二叉树的最小高度

版权声明:本文为博主原创文章,未经允许不得转载 https://blog.csdn.net/qq_34793133/article/details/82881231

题目描述

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.

翻译:

给定一棵二叉树,求出它的最小深度。最小深度是从根节点到最近的叶节点的最短路径上的节点数。

//法一:广度优先遍历:
class Solution {
public:
    typedef TreeNode* tree;
    int run(TreeNode *root) {
        //采用广度优先搜索,或者层序遍历,找到的第一个叶节点的深度即是最浅。
      if(! root) return 0;
      queue<tree> qu;
      tree last,now;
      int level,size;
      last = now = root;
      level = 1;qu.push(root);
      while(qu.size()){
        now = qu.front();
        qu.pop();
        size = qu.size();
        if(now->left)qu.push(now->left);
        if(now->right)qu.push(now->right);
        if(qu.size()-size == 0)break;
        if(last == now){
          level++;
          if(qu.size())last = qu.back();
        }
      }
      return level;
    }
};
//用递归求二叉树高度的方法,只不过之前求树高度是求的左右子树的最大高度
class Solution {
public:
    int run(TreeNode *root) {
        if(root==nullptr)
            return 0;
        int heightOfLeft=run(root->left);
        int heightOfRight=run(root->right);
        if(heightOfLeft==0||heightOfRight==0)
            return heightOfLeft+heightOfRight+1;
        return min(heightOfLeft,heightOfRight)+1;
        
    }
};
//回溯法,也即深度优先遍历
class Solution {
public:
    static int depth;
    int run(TreeNode *root)
    {
        depth=1;
        if(root==NULL)
            return 0;
        if(root->left!=NULL)
            dfs(root->left, 1);
        if(root->right!=NULL)
            dfs(root->right, 1);
        return depth;
    }
     
    void dfs(TreeNode *r, int d)
    {
        d++;
        if(d>depth&&depth>1)
            return;
        if(r->left==NULL&&r->right==NULL&&(depth==1||d<depth))
        {
            depth=d;
            return;
        }
        if(r->left!=NULL)
            dfs(r->left, d);
        if(r->right!=NULL)
            dfs(r->right, d);
        return;
    }
};
int Solution::depth=1;

猜你喜欢

转载自blog.csdn.net/qq_34793133/article/details/82881231