当前位置 : 首页 » 文章分类 :  算法  »  LeetCode.226.Invert Binary Tree 反转二叉树

LeetCode.226.Invert Binary Tree 反转二叉树

题目描述

226 Invert Binary Tree
https://leetcode-cn.com/problems/invert-binary-tree/

Invert a binary tree.

Example:

Input:

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

Output:

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

Trivia:
This problem was inspired by this original tweet by Max Howell:

Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off.


解题过程

反转二叉树,典型的递归

public TreeNode invertTree(TreeNode root) {
    if (null == root || (null == root.left && null == root.right)) {
        return root;
    }
    TreeNode temp = root.right;
    root.right = invertTree(root.left);
    root.left = invertTree(temp);
    return root;
}

GitHub代码

algorithms/leetcode/leetcode/_226_InvertBinaryTree.java
https://github.com/masikkk/algorithms/blob/master/leetcode/leetcode/_226_InvertBinaryTree.java


上一篇 LeetCode.235.Lowest Common Ancestor of BST BST的最近公共祖先

下一篇 LeetCode.112.Path Sum 二叉树的路径和

阅读
评论
135
阅读预计1分钟
创建日期 2020-01-26
修改日期 2020-01-26
类别

页面信息

location:
protocol:
host:
hostname:
origin:
pathname:
href:
document:
referrer:
navigator:
platform:
userAgent:

评论