how can i flip over binary tree? I recently came across this problem, and all my attempts to do it adequately failed. initial tree shown below.
4
/ \
2 7
/ \ / \
1 3 6 9
4
/ \
7 2
/ \ / \
9 6 3 1
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var invertTree = function(root) {
};
It will be easier with recursive method in js using DFS (depth first search) and simply swap the nodes
const trav = (currNode) => {
if (currNode === null) {
return;
}
const temp = currNode.lNode;
currNode.lNode = currNode.rNode;
currNode.rNode = temp;
trav(currNode.lNode);
trav(currNode.rNode);
};
trav(root);
return root;
For more refer to the class I wrote for more interesting methods -
Class - https://www.npmjs.com/package/@dsinjs/binary-tree
Documentation for reverse() method - https://dsinjs.github.io/binary-tree/#reverse
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With