LeetCode 104. Maximum Depth of Binary Tree

时间:2024-09-11 18:03:44

Problem:

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.

初看本题第一印象为递归写法。首先找出终止条件:node == NULL。若未进入递归终止状态,则分左子树和又子树进行递归,最终返回累加最大的值。其代码如下:

/**
* 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 ;
}
int left_node = maxDepth(root->left) + ;
int right_node = maxDepth(root->right) + ;
return (left_node > right_node)? left_node : right_node;
}
};

通过参看博客发现,还有非递归解法——通过BFS求解。将一层的节点加入到一个队列中,然后依次出队。每一层入队计数器加1,最后一层加入后即可算出总的深度。参见原博:http://blog.****.net/wangyaninglm/article/details/45700837

其代码如下:

方法一:

int maxDepth(TreeNode *root)
{
if(root == NULL)
return ; int res = ;
queue<TreeNode *> q;
q.push(root);
while(!q.empty())
{
res++;
for(int i = , n = q.size(); i < n; ++ i)
{
TreeNode *p = q.front();
q.pop(); if(p -> left != NULL)
q.push(p -> left);
if(p -> right != NULL)
q.push(p -> right);
}
} return res;
}

方法二:

int maxDepth(TreeNode *root)
{
if (root == NULL) return ;
stack<TreeNode *> gray;
stack<int> depth;
int out = ; gray.push(root);
depth.push();
while (!gray.empty()) {
TreeNode *tmp = gray.top();
int num = depth.top();
gray.pop();
depth.pop();
if (tmp->left == NULL && tmp->right == NULL) {
out = num > out ? num : out;
}
else {
if (tmp->left != NULL) {
gray.push(tmp->left);
depth.push(num + );
}
if (tmp->right != NULL) {
gray.push(tmp->right);
depth.push(num + );
}
}
}
return out;
}