(55)~[226] 翻转二叉树

89 阅读1分钟

这个我首先是想到了递归,但是思路没有,感觉迭代也行.最后看了解析,发现递归的集中写法,进行了一步一步的优化.从执行速度和消耗内存的时间来说,迭代没有递归高效,也可能是我写的迭代不好

方法一 迭代

var invertTree = function (root) {
	if (!root) {
		return null;
	}

	const s = [root];
	while (s.length) {
		const node = s.shift();
		[node.right, node.left] = [node.left, node.right]

		node.left && s.push(node.left);
		node.right && s.push(node.right);
	}

	return root;
};

方法二 递归

var invertTree = function (root) {
	if (!root) {
		return null;
	}

	// 递归 方法
	// 1 首先储存 左右节点
	/* 	// ---- 1----- start
		const left = root.left;
		const right = root.right;
		// 然后反转
		root.left = right;
		root.right = left;
		// ---- 1----- end */

/* 	// 2 上面四行代码可以优化 只保存一个变量
	const left = root.left;
	// 这个时候root.right 还是原先的右边
	root.left = root.right;
	root.right = left;// 这个left就需要之前储存的了 因为显得left 上一步一景被赋值成right了
	// ---- 2----- end */

	// 3还可以被优化 用结构赋值

	[root.right, root.left] = [root.left, root.right]



	// 递归左右节点
	invertTree(root.left);
	invertTree(root.right);

	return root;
};