-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
61 additions
and
1 deletion.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
//coding:utf-8 | ||
/*********************************************************** | ||
Program: | ||
Description: Typical DFS solution | ||
Shanbo Cheng: cshanbo@gmail.com | ||
Date: 2017-03-26 14:29:19 | ||
Last modified: 2017-03-26 14:29:43 | ||
GCC version: 4.9.3 | ||
***********************************************************/ | ||
|
||
class Solution { | ||
public: | ||
int maxdiadepth = 0; | ||
|
||
int dfs(TreeNode* root){ | ||
if(root == NULL) return 0; | ||
|
||
int leftdepth = dfs(root->left); | ||
int rightdepth = dfs(root->right); | ||
|
||
if(leftdepth + rightdepth > maxdiadepth) maxdiadepth = leftdepth + rightdepth; | ||
return max(leftdepth +1, rightdepth + 1); | ||
} | ||
|
||
int diameterOfBinaryTree(TreeNode* root) { | ||
dfs(root); | ||
|
||
return maxdiadepth; | ||
} | ||
}; |
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
//coding:utf-8 | ||
/*********************************************************** | ||
Program: Subtree of another tree | ||
Description: Standard dfs solution | ||
Shanbo Cheng: cshanbo@gmail.com | ||
Date: 2017-05-10 09:48:57 | ||
Last modified: 2017-05-10 09:51:51 | ||
GCC version: 4.9.3 | ||
***********************************************************/ | ||
|
||
class Solution { | ||
public: | ||
bool isSubtree(TreeNode* s, TreeNode* t) { | ||
return !t || s && (same(s, t) || isSubtree(s->left, t) || isSubtree(s->right, t)); | ||
} | ||
|
||
private: | ||
bool isSameTree(TreeNode* s, TreeNode* t) { | ||
return !s ? !t : t && s->val == t->val && isSameTree(s->left, t->left) && isSameTree(s->right, t->right); | ||
} | ||
}; |