leetcode 翻转二叉树

78 阅读1分钟

翻转一棵二叉树。

示例:

输入:

     4
   /   \
  2     7
 / \   / \
1   3 6   9
输出:

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

备注: 这个问题是受到 Max Howell 的 原问题 启发的 :

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

我的算法实现为:

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {TreeNode}
 */
var invertTree = function(root) {
  if (root === null) {
    return null;
  }
  let temp = root.left;
  root.left = root.right;
  root.right = temp;
  invertTree(root.left);
  invertTree(root.right);
  return root;
};

不知道为啥我使用 go 语言居然只使用了 0 s :

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func invertTree(root *TreeNode) *TreeNode {
  if (root == nil) {
    return nil;
  }
  root.Left, root.Right = root.Right, root.Left;
  invertTree(root.Left);
  invertTree(root.Right);
  return root;
}

代码就是使用递归的方式,很简单,如果是空就直接返回,如果不是就交换左右孩子即可,然后以此类推即可,最后返回当前节点。这里的返回值主要就是看传入返回值,比如说我们传入的跟节点,肯定是不希望最后得到的是其他的值,所以直接返回传入的值即可。

王尼玛的讲解翻转二叉树

第二个方法也就是广度优先遍历,我基本上忘了,找时间补回来。


来源:力扣(LeetCode)