/**
* 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:
vector<int> getLeaves(TreeNode * root){
vector<int> v;
// traverse the tree using preorder traversal. Store all nodes into a vector.
if (root == nullptr){
return v;
}
stack<TreeNode*> s;
TreeNode * curr = root;
while (!s.empty() || curr){
// pre-order traversal
if (curr->left == nullptr && curr->right == nullptr){
// found a leave node
v.push_back(curr->val);
curr = s.top();
s.pop();
}
else if (curr->right != nullptr){
s.push(curr->right);
curr = curr->left;
}
}
return v;
}
bool leafSimilar(TreeNode* root1, TreeNode* root2) {
vector<int> v1, v2;
v1 = getLeaves(root1);
v2 = getLeaves(root2);
return (v1 == v2);
}
};
Errors: Segmentation fault because I did not check for empty stack, also null pointer needs to check. also did not exhaust all conditions in the if else statements.
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.