题目地址(226. 翻转二叉树)
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),但是您却无法在面试时在白板上写出翻转二叉树这道题,这太糟糕了。
前置知识
公司
- 暂无
思路
关键点
代码
- 语言支持:Java
递归法:
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/class Solution {public TreeNode invertTree(TreeNode root) {if (root == null) {return null;}swap(root);invertTree(root.left);invertTree(root.right);return root;}// 这里传入交换的不是root的左右节点 而是吧root传进来再交换其中的左右节点public void swap(TreeNode root) {TreeNode temp = root.left;root.left = root.right;root.right = temp;}}
复杂度分析
令 n 为数组长度。
- 时间复杂度:
#card=math&code=O%28n%29&id=aRnOf)
- 空间复杂度:
#card=math&code=O%28n%29&id=xT9xn)
