Created
September 26, 2018 04:26
-
-
Save zziz/9c13f3bc3c6efba58a2cfb0660190eff to your computer and use it in GitHub Desktop.
Binary Tree traversal in C++
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
// Pre-order traversal | |
/** | |
* 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 { | |
vector<int> poResult; | |
public: | |
vector<int> preorderTraversal(TreeNode* root) { | |
if(root) poResult.push_back(root->val); | |
if(root) preorderTraversal(root->left); | |
if(root) preorderTraversal(root->right); | |
return poResult; | |
} | |
}; | |
// In-order traversal | |
/** | |
* 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 { | |
vector<int> ioResult; | |
public: | |
vector<int> inorderTraversal(TreeNode* root) { | |
if(root) inorderTraversal(root->left); | |
if(root) ioResult.push_back(root->val); | |
if(root) inorderTraversal(root->right); | |
return ioResult; | |
} | |
}; | |
// Post-order traversal | |
/** | |
* 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 { | |
vector<int> poResult; | |
public: | |
vector<int> postorderTraversal(TreeNode* root) { | |
if(root) postorderTraversal(root->left); | |
if(root) postorderTraversal(root->right); | |
if(root) poResult.push_back(root->val); | |
return poResult; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment