劍指offer-二叉樹的深度

題目:spa

輸入一棵二叉樹,求該樹的深度。從根結點到葉結點依次通過的結點(含根、葉結點)造成樹的一條路徑,最長路徑的長度爲樹的深度。code

連接:blog

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

代碼:get

心血來潮用棧實現了一下樹的後序遞歸遍歷io

 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 };*/
10 class Solution {
11 public:
12     int TreeDepth(TreeNode* pRoot)
13     {
14         if(pRoot == NULL){
15             return 0;
16         }
17         stack<TreeNode*> st;
18         stack<bool> fst;
19         TreeNode *top = pRoot;
20         bool ftop;
21         int maxDepth = 0;
22         while(top != NULL || !st.empty()){
23             while(top != NULL){
24                 st.push(top);
25                 fst.push(true);
26                 top = top->left;
27             }
28 
29             top = st.top();
30             ftop = fst.top();
31             
32             st.pop();
33             fst.pop();
34             if(ftop){
35                 st.push(top);
36                 fst.push(false);
37                 
38                 if(top->right == NULL && st.size() > maxDepth){
39                     maxDepth = st.size();
40                 }
41                 top = top->right;
42             }else{
43                 top = NULL;
44             }
45             
46         }
47         
48         return maxDepth;
49     }
50 };
相關文章
相關標籤/搜索