Leetcode Practice-Finding the depth of a binary tree-maximu Depth of binary trees

Source: Internet
Author: User

Main topic:

Very simple, just need to find the maximum depth of a binary tree, it seems that there is no time and space requirements.

Solution Method:

More simple, only need to follow the width first method to find, here I use a queue to save the node to be expanded, B to save a expanded node, and then use the T intermediate variable to exchange A and B, until a queue is empty, the end.
Note that the boundary condition, when Root=null, should return 0.

#include <iostream>#include <queue>using namespace STD;//definition for a binary tree node.structTreeNode {intVal   TreeNode *left;   TreeNode *right; TreeNode (intx): Val (x), left (null), right (null) {}};classSolution { Public:intMaxDepth (treenode* root) {intdeep=0; queue<TreeNode*>A queue<TreeNode*>b queue<TreeNode*>Tif(root!=null) deep=deep+1;Else            returnDeep A.push (root); while(!a.empty ()) {//When at least one of the two queues is not empty,            //List all sub-nodes in a            //Put the child node of a in B,            //Exchange A and B             while(!a.empty ()) {treenode* node=a.front ();if(node->left!=null) B.push (node->left);if(node->right!=null) B.push (node->right);            A.pop ();            } t=a;            A=b; b=t;if(!a.empty ()) deep=deep+1; }returnDeep }};intMain () {cout<<"Just copy the header file and the solution class.!"<< Endl;//test case, compare trouble, do not write, above code remove struct definition can AC    return 0;}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode Practice-Finding the depth of a binary tree-maximu Depth of binary trees

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.