LeetCode 104. Maximum Depth of Binary Tree (C++)

来源:互联网 发布:淘宝店运营方案论文 编辑:程序博客网 时间:2024/06/05 03:41

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

方法一: 深度优先遍历

/** * 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) {        int maxLvl = 0;        dfs(root, maxLvl, 0);        return maxLvl;    }        void dfs(TreeNode* root, int& max, int level) {        if(!root) return;        if(level+1 > max) max = level+1;        dfs(root->left, max, level+1);        dfs(root->right, max, level+1);    }};

方法二:广度优先遍历, 用一个queue也可以做到分层遍历。

class Solution {public:    int maxDepth(TreeNode* root) {        if(!root) return 0;        int maxlvl = 0;        queue<TreeNode*> nQueue;        nQueue.push(root);        while (!nQueue.empty()) {            ++maxlvl;            for(int i=0, n=nQueue.size(); i < n; ++i) {                TreeNode* cur = nQueue.front();                nQueue.pop();                if (cur->left) nQueue.push(cur->left);                if (cur->right) nQueue.push(cur->right);            }        }        return maxlvl;    }};


原创粉丝点击