I, entitled Description
Topic 226. Invert Binary Tree, flip a binary tree. The difficulty is Easy!
Second, my answer
This topic, and traverse binary tree is similar. A recursive (before, during and after preorder, can be traversed by the layer):
class Solution{
public:
TreeNode* invertTree(TreeNode* root){
if(root ==NULL) return root;
TreeNode * p = root->left;
root->left = root->right;
root->right = p;
root->left = invertTree(root->left);
root->right = invertTree(root->right);
return root;
}
};
Properties are as follows:
Runtime: 4 ms, faster than 65.13% of C++ online submissions for Invert Binary Tree.
Memory Usage: 10 MB, less than 5.45% of C++ online submissions for Invert Binary Tree.
Third, the optimization measures
Non-recursive algorithm, implemented in breadth-first traversal of the following:
class Solution{
public:
//non-recursive using level
TreeNode* invertTree(TreeNode* root){
if(root == NULL) return root;
queue<TreeNode*> q;
TreeNode* tmp,*cur;
q.push(root);
while(! q.empty()){
cur = q.front();
q.pop();
tmp = cur->left;
cur->left = cur->right;
cur->right = tmp;
if(cur->left !=NULL ){
q.push(cur->left);
}
if(cur->right != NULL){
q.push(cur->right);
}
}
return root;
}
};
Properties are as follows:
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Invert Binary Tree.
Memory Usage: 10.2 MB, less than 5.45% of C++ online submissions for Invert Binary Tree.