226. 翻转二叉树

题目描述

翻转一棵二叉树。

示例:

输入:

1     4
2   /   \
3  2     7
4 / \   / \
51   3 6   9

输出:

1     4
2   /   \
3  7     2
4 / \   / \
59   6 3   1

备注:

谷歌:我们90%的工程师使用您编写的软件(Homebrew),但是您却无法在面试时在白板上写出翻转二叉树这道题,这太糟糕了。

来源:力扣(LeetCode)

思路

遍历树(随便怎么遍历),然后将左右子树交换位置。

关键点解析

  • 递归简化操作

  • 如果树很高,建议使用栈来代替递归

  • 这道题目对顺序没要求的,因此队列数组操作都是一样的,无任何区别

代码

 1/*
 2 * @lc app=leetcode id=226 lang=javascript
 3 *
 4 * [226] Invert Binary Tree
 5 *
 6 * https://leetcode.com/problems/invert-binary-tree/description/
 7 *
 8 * algorithms
 9 * Easy (57.14%)
10 * Total Accepted:    311K
11 * Total Submissions: 540.6K
12 * Testcase Example:  '[4,2,7,1,3,6,9]'
13 *
14 * Invert a binary tree.
15 *
16 * Example:
17 *
18 * Input:
19 *
20 *
21 * ⁠    4
22 * ⁠  /   \
23 * ⁠ 2     7
24 * ⁠/ \   / \
25 * 1   3 6   9
26 *
27 * Output:
28 *
29 *
30 * ⁠    4
31 * ⁠  /   \
32 * ⁠ 7     2
33 * ⁠/ \   / \
34 * 9   6 3   1
35 *
36 * Trivia:
37 * This problem was inspired by this original tweet by Max Howell:
38 *
39 * Google: 90% of our engineers use the software you wrote (Homebrew), but you
40 * can’t invert a binary tree on a whiteboard so f*** off.
41 *
42 */
43/**
44 * Definition for a binary tree node.
45 * function TreeNode(val) {
46 *     this.val = val;
47 *     this.left = this.right = null;
48 * }
49 */
50/**
51 * @param {TreeNode} root
52 * @return {TreeNode}
53 */
54var invertTree = function(root) {
55  if (!root) return root;
56  // 递归
57  //   const left = root.left;
58  //   const right = root.right;
59  //   root.right = invertTree(left);
60  //   root.left = invertTree(right);
61  // 我们用stack来模拟递归
62  // 本质上递归是利用了执行栈,执行栈也是一种栈
63  // 其实这里使用队列也是一样的,因为这里顺序不重要
64
65  const stack = [root];
66  let current = null;
67  while ((current = stack.shift())) {
68    const left = current.left;
69    const right = current.right;
70    current.right = left;
71    current.left = right;
72    if (left) {
73      stack.push(left);
74    }
75    if (right) {
76      stack.push(right);
77    }
78  }
79  return root;
80};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值