原题链接:https://leetcode-cn.com/problems/invert-binary-tree/
解题思路:
使用递归首先要思考,当前递归函数运行的是第n次递归,那么当前要做哪些处理。先考虑的是,假设此时遍历到了最后一个节点为null,要给递归设置终止条件。在当前递归,将子节点互换,并使用新的子节点进行下一层递归。
function recursion(node
) {
if (!node
) {
return;
}
const temp
= node
.left
;
node
.left
= node
.right
;
node
.right
= temp
;
recursion(node
.left
);
recursion(node
.right
);
}
var invertTree = function (root
) {
recursion(root
);
return root
;
};