Created
December 23, 2018 01:18
-
-
Save qiaoxu123/7de9641a6868422956d1a875ee7afc68 to your computer and use it in GitHub Desktop.
考察二叉树的遍历,使用递归形式实现。
自己写的基本和最优相同,只不过有些语句没有优化。test1.cpp为自己的,test2.cpp为参考改进过得
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
/** | |
* 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 depthLeft = 0,depthRight = 0; | |
if(root == NULL) return 0; | |
if(root->left == NULL && root->right == NULL) | |
return 1; | |
depthLeft = maxDepth(root->left); | |
depthRight = maxDepth(root->right); | |
return depthLeft >= depthRight ? depthLeft + 1 : depthRight + 1; | |
} | |
}; |
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
/** | |
* 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) { | |
return root == NULL ? 0: max(maxDepth(root -> left),maxDepth(root -> right)) + 1; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment