Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along, the longest path from the root node to the farthest leaf node.
Analysis: Finding the maximum depth of a binary tree
Solution One: It is easy to think of recursion (depth-first search)
(1) If the root node is empty, return 0; otherwise go to (2)
(2) L = maximum depth of the left subtree; R = Maximum depth of right subtree; return Max (L, R) + 1;
1 /**2 * Definition for a binary tree node.3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten classSolution { One Public: A intMaxDepth (treenode*root) { - if(Root = =NULL) - return 0; the intL = maxDepth (root->Left ); - intR = maxDepth (root->Right ); - returnMax (L, R) +1; - } +};
Solution Two: I think you can also use Breadth First search: Layer I if the node is not empty, then the depth plus 1 ... The maximum depth is the number of layers in this tree.
1 classSolution {2 Public:3 intMaxDepth (treenode*root) {4 if(Root = =NULL)5 return 0;6 intdepth =0;7Queue<treenode*>Node_que;8treenode*temp;9 Node_que.push (root);Ten while(!Node_que.empty ()) { One intSize =node_que.size (); A while(size--){ -temp =Node_que.front (); - Node_que.pop (); the if(Temp->left! =NULL) -Node_que.push (temp->Left ); - if(Temp->right! =NULL) -Node_que.push (temp->Right ); + } -depth++; + } A returndepth; at - } -};
Leetcode 104. Maximum Depth of binary tree (maximum depth of binary trees)