美文网首页
104. Maximum Depth of Binary Tre

104. Maximum Depth of Binary Tre

作者: 刘小小gogo | 来源:发表于2018-08-20 22:27 被阅读0次
image.png

解法一:递归:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(root == NULL) return 0;
        int left = root->left ?  maxDepth(root->left) : 0;
        int right = root->right ?  maxDepth(root->right) : 0;
        return max(left, right) + 1;
        
    }
};

解法二:层次遍历

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(root == NULL) return 0;
        queue<vector<TreeNode*>> q;
        vector<TreeNode*> cur;
        cur.push_back(root);
        q.push(cur);
        int ans = 0;
        while(!q.empty()){
            vector<TreeNode*> list = q.front();
            q.pop();
            vector<TreeNode*> tmp;
            ans++;
            cout<<ans<<endl;
            for(int i = 0; i < list.size();i++){
                if(list[i]->left) tmp.push_back(list[i]->left);
                if(list[i]->right) tmp.push_back(list[i]->right);
            }
            if(tmp.size()) q.push(tmp);
        }
        return ans;
    }
};

相关文章

网友评论

      本文标题:104. Maximum Depth of Binary Tre

      本文链接:https://www.haomeiwen.com/subject/xperiftx.html