85 lines
2.0 KiB
JavaScript
85 lines
2.0 KiB
JavaScript
/**
|
||
* 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)
|
||
* }
|
||
*/
|
||
/**
|
||
* https://leetcode.cn/problems/invert-binary-tree/?envType=study-plan-v2&envId=top-interview-150
|
||
* @param {TreeNode} root
|
||
* @return {TreeNode}
|
||
*/
|
||
const invertTree = function (root) {
|
||
|
||
};
|
||
|
||
/*
|
||
利用递归来抽象问题,交换一颗树的左右子树不就可以做到翻转了,函数f1只做单一的功能,就是反转
|
||
一颗二叉树,递归调用就可以翻转从根节点开始的整棵树
|
||
*/
|
||
|
||
function f1(root) {
|
||
if (!root) return; // 如果当前节点为空,直接返回
|
||
|
||
const left = root.left;
|
||
const right = root.right;
|
||
|
||
// 交换左右两棵树的位置
|
||
root.left = right;
|
||
root.right = left;
|
||
|
||
// 递归调用
|
||
f1(root.left);
|
||
f1(root.right);
|
||
}
|
||
|
||
/*
|
||
使用bfs来翻转一颗树
|
||
*/
|
||
function f2(root) {
|
||
if (!root) return root;
|
||
|
||
const queue = [root]; // bfs所需要的队列
|
||
|
||
while (queue.length > 0) {
|
||
// 从队列中取出节点,实际顺序为从上到下,从左到右(BFS)
|
||
const node = queue.shift();
|
||
// 交换左右两个节点
|
||
const tmp = node.left;
|
||
node.left = node.right;
|
||
node.right = tmp;
|
||
|
||
// 如果左子节点存在,加入队列
|
||
if (node.left) queue.push(node.left);
|
||
// 如果右子节点存在,加入队列
|
||
if (node.right) queue.push(node.right);
|
||
}
|
||
return root;
|
||
}
|
||
|
||
/*
|
||
使用DFS来翻转一颗树
|
||
*/
|
||
|
||
function f3(root) {
|
||
if (!root) return root;
|
||
const stack = [root]; // dfs所需要的栈
|
||
|
||
while (stack.length > 0) {
|
||
// 从栈中取出节点,DFS
|
||
const node = stack.pop();
|
||
|
||
// 交换左右两棵子树
|
||
const tmp = node.left;
|
||
node.left = node.right;
|
||
node.right = tmp;
|
||
|
||
// 如果字节的不为空压入栈继续dfs,
|
||
if (node.left) stack.push(node.left);
|
||
if (node.right) stack.push(node.right);
|
||
}
|
||
return root;
|
||
}
|