Created
March 26, 2019 07:51
-
-
Save sonsongithub/1477914643b339bf7dd98c250f2d0a76 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <vector> | |
| #include <iostream> | |
| #include <unordered_map> | |
| using namespace std; | |
| // Definition for a binary tree node. | |
| struct TreeNode { | |
| int val; | |
| TreeNode *left; | |
| TreeNode *right; | |
| TreeNode(int x) : val(x), left(NULL), right(NULL) {} | |
| }; | |
| class Solution { | |
| public: | |
| int maxDepth(TreeNode* root) { | |
| int max = 1; | |
| if (root == NULL) | |
| return 1; | |
| search(root, 1, &max); | |
| return max; | |
| } | |
| int search(TreeNode* root, int depth, int* max) { | |
| if (root->left == NULL && root->right == NULL) { | |
| if (depth > *max) | |
| *max = depth; | |
| return depth; | |
| } else { | |
| if (root->left != NULL) { | |
| search(root->left, depth+1, max); | |
| } | |
| if (root->right != NULL) { | |
| search(root->right, depth+1, max); | |
| } | |
| return depth; | |
| } | |
| } | |
| }; | |
| int main(int argc, char**argv) { | |
| // [3,9,20,null,null,15,7], | |
| auto node1 = TreeNode(3); | |
| auto node2 = TreeNode(9); | |
| auto node3 = TreeNode(20); | |
| auto node4 = TreeNode(15); | |
| auto node5 = TreeNode(7); | |
| node1.left = &node2; | |
| node1.right = &node3; | |
| node3.left = &node4; | |
| node3.right = &node5; | |
| auto obj = Solution(); | |
| int a = obj.maxDepth(&node1); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment