標籤:root 入隊 public 方法 非遞迴 null gray 最大 ber
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