Maximum Depth of Binary TreeTotal accepted:59837 Total submissions:132940my submissions QuestionSolution
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.
Hide TagsTree Depth-first SearchHas you met this question in a real interview? Yes No
Discuss
1. Use recursive methods to do
#include <iostream> #include <vector>using namespace Std;struct treenode{int val; TreeNode *left; TreeNode *right; TreeNode (int x): Val (x), left (null), right (NULL) {}};//is done recursively (somewhat like the sense of dynamic planning) int max (int a,int b); int maxDepth (TreeNode *root) {int left,right;if (root==null) return 0;left=maxdepth (root->left);//Zuozi depth right=maxdepth (root->right) ;//The depth of the right subtree return 1+max (left,right);//Select the one that is large in depth, plus one of its own, for itself this node depth}int max (int a,int b) {if (a>=b) return A; Elsereturn b;} int main (int argc,char** argv) {}
2. Use a queue to do
#include <iostream> #include <vector> #include <queue>using namespace Std;struct treenode{int val; TreeNode *left; TreeNode *right; TreeNode (int x): Val (x), left (null), right (null) {}};//in the form of a queue, traversing the two-fork tree one layer at a queue, and recording the number of layers int maxDepth (TreeNode * Root) {if (root==null) return 0;int deep=0;//depth int row_size=1;//The number of elements per layer (first layer has only one root node) queue<treenode*> temp;// The queue used by the algorithm. Temp.push (Root), while (!temp.empty ())//until the queue is empty to stop {treenode* temp_node;while (row_size--)//to traverse each layer sequentially, Each element in the next layer is queued and the queue of the previous layer {//is queued. Temp_node=temp.front (); if (temp_node->left!=null) Temp.push (temp_node->left); if (temp_node->right!=null) Temp.push (temp_node->right); Temp.pop ();} Row_size=temp.size ();//record the number of elements in this layer deep+=1;//record depth}return deep;} int main (int argc,char** argv) {}
Leetcode--maximum Depth of Binary Tree (recursive,)