其他分享
首页 > 其他分享> > LeetCode 226. Invert Binary Tree

LeetCode 226. Invert Binary Tree

作者:互联网

226. Invert Binary Tree(翻转二叉树)

链接

https://leetcode-cn.com/problems/invert-binary-tree

题目

翻转一棵二叉树。

示例:

输入:

 4

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

 4

/ 7 2
/   / 9 6 3 1
备注:
这个问题是受到 Max Howell 的 原问题 启发的 :

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

思路

简单题目,对于每一个结点,都交换左右子节点,然后交换完整棵树就结束了。设置一个临时结点,然后递归即可。

代码

  public class TreeNode {

    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
      val = x;
    }
  }

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

标签:right,TreeNode,invertTree,Invert,Tree,二叉树,226,root,left
来源: https://www.cnblogs.com/blogxjc/p/12488633.html