Binary tree? Flip!
Topic
flip a binary tree.
Examples
Example:
Input:
-----. 4
---- / \
---- 2-7
- / \ - /
\ -1369
Output:
----. 4
---- / \
--7 - 2
- / \ - / \
-9631
Topic analysis
- Flip binary
left and right subtrees symmetric swapping
- A binary symmetric
about subtree pointer exchange - Symmetric binary tree
which sub-trees are symmetrical ==> Recursive
Problem-solving ideas
Process
for the current root
exchange pointers to left and right subtrees content
- Left subtree presence ==> symmetrical left subtree
- Right subtree presence ==> symmetry of the right subtree
code show as below
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(!root) return root;
TreeNode* temp;
temp = root->left;
root->left = root->right;
root->right = temp;
if(root->left) invertTree(root->left); //递归左子树对称
if(root->right) invertTree(root->right); //递归右子树对称
return root;
}
};