@
@
@Richswitch2018-09-17 19:31:40
JavaScript
@Richswitch, 2018-09-17 19:31:40

How to implement invert function for binary tree?

Hey!
It is necessary to implement the invert function for a binary tree.
Example:
Input (schematic)

:
    4
   / \
 2    7
/ \   / \
1  3 6  9

Output (schematically)
:
    4
   / \
 7    2
/ \   / \
9  6 3  1

There is such data:
const tree = {left: {value: 2}, value: 1, right:{value: 4}}

After processing by the function:
const inverted = invertTree(tree);
This object should turn out like this: I read articles on this topic, but so far I can’t figure out where to start and how to end :\
{left: {value: 4}, value: 1, right:{value: 2}}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-09-17
_

The recursion is:

const invertTree = ({ value, left, right }) => {
  const node = { value };
  if (left) {
    node.right = invertTree(left);
  }
  if (right) {
    node.left = invertTree(right);
  }
  return node;
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question