[LeetCode] Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

 

分析:就是传统意义上的二叉树高度

1 递归:

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int maxDepth(TreeNode *root) {
13 
14     if (NULL == root) return 0;
15     int leftHeight = maxDepth(root->left);
16     int rightHeight = maxDepth(root->right);
17     int height ;
18     if(leftHeight > rightHeight)
19         height = leftHeight;
20     else
21         height = rightHeight;
22     return height + 1;
23  
24     }
25 };

 框架和求最小深度一样的非递归,由于最大长度要遍历到所有也节点,所以没有减枝

 1 struct newNode{
 2     TreeNode * node;
 3     int         dep;
 4 };
 5 
 6 class Solution {
 7     public:
 8         int maxDepth(TreeNode *root) {
 9             ;
10             if(NULL == root) return 0;
11 
12             int maxDep = INT_MIN;
13 
14             stack<newNode*> stack;
15 
16             newNode *p = new newNode;
17             p->node = root;
18             p->dep = 1;
19             stack.push(p);
20 
21             while( !stack.empty())
22             {
23                 p= stack.top();
24                 stack.pop();
25 
26                 TreeNode *pNode = p->node;
27                 int dep = p->dep;
28 
29 
30                 if(pNode->left == NULL && pNode->right == NULL)
31                 {
32                     maxDep = max(maxDep, dep);
33                 }
34 
35                 if(pNode->left != NULL)
36                 {
37                     newNode *tmp = new newNode;
38                     tmp->node = pNode->left;
39                     tmp->dep = dep + 1;
40                     stack.push(tmp);
41                 }
42 
43                 if(pNode->right != NULL)
44                 {
45                     newNode *tmp = new newNode;
46                     tmp->node = pNode->right;
47                     tmp->dep = dep + 1;
48                     stack.push(tmp);
49                 }
50 
51             }
52 
53             return maxDep;
54         }
55 
56 };
原文地址:https://www.cnblogs.com/diegodu/p/3781779.html