Leetcode:minimum-depth-of-binary-tree

Leetcode:minimum-depth-of-binary-tree

Given a binary tree, find its minimumdepth.The minimum depth is the number of nodes along the shortest path from theroot node down to the nearest leaf node.

解決思路如下:

深度遍歷樹結點,遇到四種情況

(1)存在左子節點,但不存在右子節點,因爲非葉節點,還需要朝左遍歷下去,深度加1。

(2)存在右子節點,但不存在左子節點,因爲非葉節點,還需要朝右遍歷下去,深度加1。

(3)左右子節點均存在,因爲是求最小深度,因此求得的應當是左和右子節點當中深度比較小的結點。

(4)是葉結點,返回具體的深度。

代碼如下:

int run(TreeNode *root) {
        if(root==NULL)
            return 0;
        return depthnum(root,1);
    }
    
    int depthnum(TreeNode* root, int depth)
    {
        if(root->left && !root->right)
            return depthnum(root->left,++depth);
        else if(!root->left && root->right)
            return depthnum(root->right,++depth);
        else if(root->left && root->right)
        {
            depth++;
            return min(depthnum(root->left,depth),depthnum(root->right,depth));
        }
        else 
            return depth;
}

網上還提供了還有一種方法,是利用隊列按層遍歷,解題思路是按層遍歷直到找到第一個葉結點,此時的深度必爲最小。

代碼如下:

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;
    }
};




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章