leetcode 226 Flip binary tree

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
  1. A binary symmetric
    about subtree pointer exchange
  2. 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;
    }
};
Published 34 original articles · won praise 0 · Views 580

Guess you like

Origin blog.csdn.net/Luyoom/article/details/104176555