I am working on LeetCode problem 226. Invert Binary Tree:
Given the
rootof a binary tree, invert the tree, and return its root.Example 1
Input: root = [4,2,7,1,3,6,9] Output: [4,7,2,9,6,3,1]
I wrote the following C++ code, but it gives the wrong answer. I don't know whether there is a flaw in my logic.
Code
class Solution {
public:
void dfs1(TreeNode* root,vector<int> &vec){
if(root==NULL)
return;
dfs1(root->left,vec);
vec.push_back(root->val);
dfs1(root->right,vec);
}
void dfs2(TreeNode* root,vector<int> &vec,int &j) {
if(root==NULL)
return;
dfs1(root->right,vec);
root->val=vec[j];
j--;
dfs1(root->left,vec);
}
TreeNode* invertTree(TreeNode* root) {
vector<int> p;
dfs1(root,p);
int size=p.size()-1;
dfs2(root,p,size);
return root;
}
};
I am just doing an inorder traversal and pushing the values into a vector. Then again I perform an inorder traversal, but this time I am traversing the other way, that is from right to left.
