1. 程式人生 > 其它 >543&1367.二叉樹的直徑、最大深度

543&1367.二叉樹的直徑、最大深度

目錄

543.二叉樹的直徑


給定一棵二叉樹,你需要計算它的直徑長度。一棵二叉樹的直徑長度是任意兩個結點路徑長度中的最大值。這條路徑可能穿過也可能不穿過根結點。

示例:

解題思路


https://leetcode-cn.com/problems/diameter-of-binary-tree/solution/shi-pin-jie-shi-di-gui-dai-ma-de-yun-xing-guo-chen/

class Solution {
public:
    int ans=1;
    int diameterOfBinaryTree(TreeNode* root) {
        depth(root);
        return ans-1;
    }
    int depth(TreeNode* root){
        if(!root)return 0;
        int L=depth(root->left);
        int R=depth(root->right);
        ans=max(ans,L+R+1);
        return max(L,R)+1;
    }
};

1367.二叉樹的最大深度


給定一個二叉樹,找出其最大深度。二叉樹的深度為根節點到最遠葉子節點的最長路徑上的節點數。

示例:

解題思路


  • 遞迴
//遞迴法
class Solution {
public:
    int ans=0;
    int maxDepth(TreeNode* root) {
        if(!root)return 0;
        return depth(root);
    }
    int depth(TreeNode* root){
        if(!root)return 0;
        int L=depth(root->left);
        int R=depth(root->right);
        ans=max(L,R)+1;
        return ans; 
    }
};
  • 非遞迴
class Solution {
public:
    int maxDepth(TreeNode* root) {
        //層次遍歷
        if(!root)return 0;
        int maxdepth=0;int qSize=0;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            maxdepth++;  
            qSize=q.size();
            while(qSize--!=0){//tips!
                root=q.front();
                q.pop();
                if(root->left)q.push(root->left);
                if(root->right)q.push(root->right);

            } 
        }
        return maxdepth;
    }
};