Leetcode::Maximum Depth of Binary Tree
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 void Preorder( TreeNode *root, int &depth, int n ) 13 { 14 if( root ) 15 { 16 n++; 17 18 if( root->left == NULL && root->right == NULL ) 19 { 20 if( n > depth ) 21 { 22 depth = n; 23 } 24 return; 25 } 26 27 if( root->left ) 28 { 29 Preorder( root->left,depth,n); 30 } 31 32 if( root->right ) 33 { 34 Preorder( root->right,depth,n); 35 } 36 } 37 } 38 int maxDepth(TreeNode *root) { 39 // Start typing your C/C++ solution below 40 // DO NOT write int main() function 41 int depth = 0; 42 int n = 0; 43 Preorder(root,depth,n); 44 return depth; 45 46 } 47 };