Reverse binary tree

He said reverse binary tree is the binary tree left subtree right subtree call, if they have a child, then about exchange also recursive.

Therefore, the step of the binary tree is briefly reversed:

  • 1. reverse the root of the left subtree (recursively reverse function)
  • 2. Reverse the root of the right subtree (recursively reverse function)
  • 3. The exchange left and right node of the root node.

Inverted binary tree illustrated example:
Initial:


11345146-dff1c78ba4d05bc6.png
Initial Binary Tree

After the reverse:


11345146-36b5e667e5f9028e.png
After the reversal binary tree

code show as below:

public TreeNode invertTree(TreeNode root) {
        if(root==null){
            return null;
        }
        invertTree(root.left);
        invertTree(root.right);

        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        return root;
    }

Reproduced in: https: //www.jianshu.com/p/9b2390f35de6

Guess you like

Origin blog.csdn.net/weixin_33827731/article/details/91294065