Algorithms
Invert Binary Tree
seoca
2020. 11. 30. 22:51
Binary Tree(이진트리) 의 node와 그 node의 children을 invert 하는 문제.
node뿐 아니라 그 밑에 속해있는 자식들까지 swipe해야하기때문에 recursive function(재귀함수)을 사용해야한다.
Solution 1
var invertTree = function(root) {
//재귀의 정지값->root가 있을때 까지.
if(root){
swap(root); //swipe children
invertTree(root.left); //subtree의 children에게도 같은 process적용을 위해 recursive
invertTree(root.right);
}
return root;
};
var swap = function(root){
let left = root.left;
root.left = root.right;
root.right = left;
}
Solution 2.
Reference