目录
226. 翻转二叉树
思路
代码
本地代码测试
不管前方的路有多苦
只要走的方向正确
不管多么崎岖不平
都比站在原地更接近幸福
—— 24.10.21
226. 翻转二叉树
给你一棵二叉树的根节点
root
,翻转这棵二叉树,并返回其根节点。示例 1:
输入:root = [4,2,7,1,3,6,9] 输出:[4,7,2,9,6,3,1]示例 2:
输入:root = [2,1,3] 输出:[2,3,1]示例 3:
输入:root = [] 输出:[]
思路
代码
/**
* 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 static TreeNode invertTree(TreeNode root) {
fn(root);
return root;
}
private static void fn(TreeNode root) {
if (root == null) {
return;
}
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
fn(root.left);
fn(root.right);
}
}
本地代码测试
public class LeetCode226ReverseBinaryTree {
public static TreeNode invertTree(TreeNode root) {
fn(root);
return root;
}
private static void fn(TreeNode root) {
if (root == null) {
return;
}
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
fn(root.left);
fn(root.right);
}
private static void Print(TreeNode root, String indent) {
if (root == null) {
return;
}
System.out.println(indent + root.value);
Print(root.left, indent + " |-- ");
Print(root.right, indent + " |-- ");
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1,
new TreeNode(2,
new TreeNode(4),
new TreeNode(5,
new TreeNode(7), null)),
new TreeNode(3,
null,
new TreeNode(6)));
TreeNode invertedRoot = invertTree(root);
Print(invertedRoot,"");
}
}