leetcode226-翻转二叉树
leetcode 226
思路
翻转二叉树就是交换每个元素的左右节点,首先在root层交换左右节点,然后再到子树交换左右节点
方法1 层序遍历
var invertTree = function (root) {
if (!root) return root;
const queue = [root], result = [];
while(queue.length){
let len = queue.length;
while(len--){
const node = queue.shift();
// 交换左右节点
const temp = node.left;
node.left = node.right;
node.right = temp;
node.left && queue.push(node.left)
node.right && queue.push(node.right)
}
}
return root;
};
方法2 前序遍历递归法
var invertTree = function (root) {
const deep = (root) => {
if (!root) return;
const temp = root.left;
root.left = root.right;
root.right = temp;
deep(root.left)
deep(root.right)
}
deep(root)
return root;
};