226. 翻转二叉树

/**
 * 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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值