Binary tree: Will you really flip a binary tree?

226. Flip Binary Tree

Flip a binary tree.

 

 

There is a story behind this question that makes programmers sad. I heard that Max Howell, the author of Homebrew, was rejected by Google because he didn't write a flip binary tree on the whiteboard. (True and false do not judge, right to be a pleasure)

Digression

This question is a very classic question, and it is also a relatively simple question (at least you can read it).

But precisely because this question is too simple, it will be obvious at a glance. Some students did not grasp the essence and passed this question in a confused way.

If you have done this question, it is recommended to read it carefully, I believe it will be rewarding!

Ideas

We have introduced various ways to traverse the binary tree. This time we are going to flip it, and it still feels a bit confusing.

How can this be flipped?

If you want to look at the entire tree, the flip is really complicated. The entire tree is flipped with the middle line, as shown in the figure:

 

 

You can find that if you want to flip it, you can actually swap the left and right children of each node (note that the nodes under the children are swapped together).

The key lies in the traversal order. Which traversal order should be selected in the first, middle and last order? (Some students have passed this question, but don’t know what order they used)

In the process of traversal, the left and right children of each node can be flipped to achieve the overall flipping effect.

"Note that as long as you flip the left and right children of each node, you can achieve the overall flip effect."

"This question can use both pre-order traversal and post-order traversal, but middle-order traversal will not work, because middle-order traversal will flip the left and right children of some nodes twice! It is recommended to draw on paper to understand."

So is it possible to traverse the sequence? "It's still possible! As long as the traversal method of flipping the left and right children of each node is possible!"

Recursion

For the first-middle-post-order traversal of the recursive method of the binary tree , it has been explained in detail in the binary tree: front-middle-post-order recursive traversal .

Let's take the following pre-order traversal as an example, and look at the flipping process through animation:

 

 

Let's take a look at the recursive trilogy:

  1. Determine the parameters and return value of the recursive function

The parameter is the pointer to be passed into the node, no other parameters are needed. Usually the main parameters are set at this time. If you find that other parameters are needed in the recursive logic, you can add them at any time.

The return value is actually not necessary, but the pointer to the root node given in the title can directly use the function defined in the title, so the return type of the function is TreeNode*.

TreeNode* invertTree(TreeNode* root)
  1. Determine termination conditions

When the current node is empty, return

if (root == NULL) return root;
  1. Determine the logic of single recursion

Because it is a previous order traversal, the left and right child nodes are exchanged first, then the left subtree and the right subtree are reversed.

swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);

Based on this three-step recursive method, the code is basically finished, and the C++ code is as follows (preamble):

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if (root == NULL) return root;
        swap(root->left, root->right);  // 中
        invertTree(root->left);         // 左
        invertTree(root->right);        // 右
        return root;
    }
};

Iterative method

Simulate depth first traversal

Binary tree: I heard that recursion can do, so can stacks! The writing method of the front, middle and back order iteration method is given in, so the code of the following iteration method can be easily cut out locally:

The C++ code is as follows: iteration method (preorder traversal)

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if (root == NULL) return root;
        stack<TreeNode*> st;
        st.push(root);
        while(!st.empty()) {
            TreeNode* node = st.top();              // 中
            st.pop();
            swap(node->left, node->right);          
            if(node->right) st.push(node->right);   // 右
            if(node->left) st.push(node->left);     // 左
        }
        return root;
    }
};

If you don’t understand this code, you can review the binary tree: I heard that recursion can do it, so can stacks! .

We introduced the writing of the unified iteration method in Binary Tree: Unified Writing of the First, Middle and Post-Order Iteration , so this question only needs to modify the code in the text less.

The C++ code is as follows: unified writing iterative method (preorder traversal)

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        stack<TreeNode*> st;
        if (root != NULL) st.push(root);
        while (!st.empty()) {
            TreeNode* node = st.top();
            if (node != NULL) {
                st.pop();
                if (node->right) st.push(node->right);  // 右
                if (node->left) st.push(node->left);    // 左
                st.push(node);                          // 中
                st.push(NULL);
            } else {
                st.pop();
                node = st.top();
                st.pop();
                swap(node->left, node->right);          // 节点处理逻辑
            }
        }
        return root;
    }
};

If you don’t understand the above code, review the article Binary Tree: The Unified Writing Method of First, Middle and Last Iteration .

Breadth first traversal

That is, the layer sequence traversal, the layer number traversal can also flip this tree, because the layer sequence traversal can also flip the left and right children of each node. The code is as follows:

class Solution {
public:
    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;
    }
};

If you don't understand the above code, or don't know the sequence traversal of the binary tree , you can read this binary tree: the debut of the sequence traversal!

to sum up

For the problem of binary tree, before solving the problem, we must think clearly whether it is a traversal in front, middle and last order or layer order traversal.

"The big taboo of binary tree problem solving is that I have been confused (because this problem is relatively simple), but I don't know how I traversed it."

This is also the reason why the title of the binary tree is "it can be seen at a glance, and it will be discarded as soon as it is written."

For flipping the binary tree, I gave one recursion and three iterations (two simulated depth-first traversal and one level-sequence traversal). They are all the ones we have talked about before.

 

Everyone must have their own solution, but it must be a methodology, so that it can be universal and infer other things!

 

This article: https://github.com/youngyangyang04/leetcode-master already included, there is also the question Raiders leetcode brush, brush each type classic topic title sequence, mind map, you can fork into their own warehouses , empty look You will definitely gain something, if it helps you, give a star to support it!

My B station (there are algorithm videos and programming related knowledge I explained) : https://space.bilibili.com/525438321

I am Carl, a programmer, and a senior brother of Harbin Engineering. I have been engaged in technology research and development for Tencent and Baidu for many years. I used my spare time to brush leetcode. More exciting algorithm articles are available:  Code Random Thoughts.    After paying attention, reply "Java" "C++" "python" "Resume template" and so on. With the learning materials I have compiled for many years, you can add me to   WeChat , remark "personal profile" + "group review questions", and pull you into the review group (no ads, pure personal sharing), I analyze a classic topic every day. Every topic I choose is not isolated, but from the shallower to the deeper. If you follow the rhythm and read each article continuously, you will definitely be integrated.

Guess you like

Origin blog.csdn.net/youngyangyang04/article/details/108889630