题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
【思路1】递归
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 int h1 = TreeDepth(pRoot->left); 17 int h2 = TreeDepth(pRoot->right); 18 return max(h1,h2) + 1; 19 } 20 };
【思路2】DFS,用一个栈来存储结点,一个栈来存储当前深度
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 { 12 public: 13 int TreeDepth(TreeNode* pRoot) 14 { 15 if(pRoot == NULL) return 0; 16 stack<TreeNode*> nodeStack; 17 stack<int> depthStack; 18 19 nodeStack.push(pRoot); 20 depthStack.push(1); 21 22 TreeNode* node = pRoot; 23 int MaxDepth = 0; 24 int curDepth = 0; 25 26 while(!nodeStack.empty()) 27 { 28 node = nodeStack.top(); 29 nodeStack.pop(); 30 curDepth = depthStack.top(); 31 depthStack.pop(); 32 if(MaxDepth < curDepth) 33 MaxDepth = curDepth; 34 35 if(node->left != NULL) 36 { 37 nodeStack.push(node->left); 38 depthStack.push(curDepth + 1); 39 } 40 if(node->right != NULL) 41 { 42 nodeStack.push(node->right); 43 depthStack.push(curDepth + 1); 44 } 45 } 46 return MaxDepth; 47 } 48 };