Sword refers to the depth of the offer-two fork tree

Source: Internet
Author: User

Topic:

Enter a binary tree to find the depth of the tree. A path from the root node to the leaf node followed by a node (with root and leaf nodes) to form a tree, the length of the longest path is the depth of the tree.

Link:

http://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b?tpId=13&tqId=11191&rp=2&ru=/ta/ Coding-interviews&qru=/ta/coding-interviews/question-ranking

Code:

The whim uses the stack to realize the sequential recursive traversal of the tree.

1 /*2 struct TreeNode {3 int val;4 struct TreeNode *left;5 struct TreeNode *right;6 TreeNode (int x):7 val (x), left (null), right (null) {8     }9 };*/Ten classSolution { One  Public: A     intTreedepth (treenode*proot) -     { -         if(Proot = =NULL) { the             return 0; -         } -Stack<treenode*>St; -stack<BOOL>FST; +TreeNode *top =Proot; -         BOOLFtop; +         intMaxDepth =0; A          while(Top! = NULL | |!St.empty ()) { at              while(Top! =NULL) { - St.push (top); -Fst.push (true); -top = top->Left ; -             } -  intop =st.top (); -Ftop =fst.top (); to              + St.pop (); - Fst.pop (); the             if(ftop) { * St.push (top); $Fst.push (false);Panax Notoginseng                  -                 if(Top->right = = NULL && st.size () >maxDepth) { theMaxDepth =st.size (); +                 } Atop = top->Right ; the}Else{ +top =NULL; -             } $              $         } -          -         returnmaxDepth; the     } -};

Sword refers to the depth of the offer-two fork tree

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.