LeetCode 226. Invert Binary Tree

北慕城南 提交于 2020-03-13 20:54:51

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;
  }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!