首页 > 代码库 > LeetCode 104. Maximum Depth of Binary Tree
LeetCode 104. Maximum Depth of Binary Tree
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 0; } int left_node = maxDepth(root->left) + 1; int right_node = maxDepth(root->right) + 1; return (left_node > right_node)? left_node : right_node; } };
通过参看博客发现,还有非递归解法——通过BFS求解。将一层的节点加入到一个队列中,然后依次出队。每一层入队计数器加1,最后一层加入后即可算出总的深度。参见原博:http://blog.csdn.net/wangyaninglm/article/details/45700837
其代码如下:
方法一:
int maxDepth(TreeNode *root) { if(root == NULL) return 0; int res = 0; queue<TreeNode *> q; q.push(root); while(!q.empty()) { res++; for(int i = 0, 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 0; stack<TreeNode *> gray; stack<int> depth; int out = 0; gray.push(root); depth.push(1); 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 + 1); } if (tmp->right != NULL) { gray.push(tmp->right); depth.push(num + 1); } } } return out; }
LeetCode 104. Maximum Depth of Binary Tree
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。