LeetCode - Flip Binary Tree

Title description:

Flip a binary tree.
Example:
Input:
4
/ /
2 7
/ / / /
1 3 6 9
Output:
4
/ /
7 2
/ / / /
9 6 3 1

Thinking analysis:

If you want to exchange a binary tree, you only need to swap the positions of its left and right children when traversing each node to complete the inversion of the entire binary tree. Note that this problem cannot use the inverted binary tree traversed in order.

Recursion method:

By traversing each node first, and then swapping the left and right children, the entire binary tree is flipped.
Code:

    TreeNode* invertTree(TreeNode* root) {
    
    
            if(root==NULL) return root;         //递归终止条件
            swap(root->left,root->right);       //中,
            invertTree(root->left);				//左
            invertTree(root->right);			//右
            return root;

DFS flip binary tree

Code:

    TreeNode* invertTree(TreeNode* root) {
    
    
        if(root == NULL) return root;
        stack<TreeNode*> sta;           //深度遍历需要借助栈
        sta.push(root);                //先把头节点放到栈中去;
        while(!sta.empty())
        {
    
    
            TreeNode* node=sta.top();   //获取到栈顶节点,然后弹出
            sta.pop();               
            swap(node->left,node->right);        //交换栈顶节点左右孩子
            if(node->right)  sta.push(node->right);     //先压右孩子,因为栈是先进后出
            if(node->left)   sta.push(node->left);      //在压左孩子
        }
        return root;
    }

Sequence first traversal inverted binary tree

Code:

        TreeNode* invertTree(TreeNode* root) {
    
    
            queue<TreeNode*> que;              //层序遍历需要借助队列
            if(root!=NULL)  que.push(root);
            while(!que.empty())
            {
    
    
                int size=que.size();
                for(int i=0;i<size;i++)
                {
    
    
                    TreeNode* node=que.front();
                    que.pop();
                    //只要在遍历每个节点的时候,交换子节点的左右位置即可;
                    swap(node->left,node->right);
                    if(node->left) que.push(node->left);                //因为是队列,所以先左再右
                    if(node->right) que.push(node->right);
                }
            }
            return root;
        }

to sum up:

In fact, for reversing a binary tree, the core idea is to traverse each node of the binary tree, and then exchange the positions of the left and right children.

Guess you like

Origin blog.csdn.net/ALITAAAA/article/details/109367684