/**
* 226. 翻转二叉树
* @author wsq
* @date 2020/09/16
翻转一棵二叉树。
示例:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
链接:https://leetcode-cn.com/problems/invert-binary-tree
*/
package com.wsq.leetcode;
// Definition for a binary tree node.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class InvertTree {
/**
* 翻转二叉树(递归方式实现)
* 翻转以root根节点的二叉树,大致流程如下:
* 1. 翻转root的左子树
* 2. 翻转root的右子树
* 3. 修改root的左右子树的指针(root.left->原root.right
* root.right->原root.left)
* @param root
* @return
*/
public TreeNode invertTree(TreeNode root) {
if(root == null) {
return null;
}
if(root.left == null && root.right == null) {
return root;
}
TreeNode tmpNode = invertTree(root.left);
root.left = invertTree(root.right);
root.right = tmpNode;
return root;
}
public static void main(String[] args) {
int[] a = {4,2,7,1,3,6,9};
TreeNode root = buildTree(a, 0);
InvertTree it = new InvertTree();
it.invertTree(root);
}
public static TreeNode buildTree(int[] a, int pos) {
if(pos >= a.length) {
return null;
}
TreeNode root = new TreeNode(a[pos]);
root.left = buildTree(a, 2 * pos + 1);
root.right = buildTree(a, 2 * pos + 2);
return root;
}
}
226. 翻转二叉树
最新推荐文章于 2022-06-25 21:43:11 发布