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