二叉树反转java实现

项目github地址:bitcarmanlee easy-algorithm-interview-and-practice
欢迎大家star,留言,一起学习进步

反转二叉树是数据结构中一种经典的操作。如下图所以,反转二叉树就是交换所有节点的左右子树。
这里写图片描述

具体代码实现如下:

节点类

/**
 * Created by wanglei on 17/8/5.
 */
public class TreeNode {

    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;
    }
}

import java.util.LinkedList;
import java.util.List;

/**
 * Created by wanglei on 17/8/5.
 */
public class Solution {

    private int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    private static List<TreeNode> nodeList = null;

    public void createTree() {
        nodeList = new LinkedList();
        for(int index = 0; index < array.length; index++) {
            nodeList.add(new TreeNode(array[index]));
        }
        //最后一个父节点在数组中的索引
        int lastParentIndex = array.length / 2 - 1;
        for(int parentInex = 0; parentInex < lastParentIndex; parentInex++) {
            nodeList.get(parentInex).left = nodeList.get(parentInex * 2 + 1);
            nodeList.get(parentInex).right = nodeList.get(parentInex * 2 + 2);
        }
        // 最后一个父节点:因为最后一个父节点可能没有右孩子,所以单独拿出来处理
        // 左孩子
        nodeList.get(lastParentIndex).left = nodeList.get(lastParentIndex * 2 + 1);
        // 右孩子
        if(array.length % 2 == 1) {
            nodeList.get(lastParentIndex).right = nodeList.get(lastParentIndex * 2 + 2);
        }
    }

    // 层次遍历
    public void levelTraverse(TreeNode root) {
        if(root == null) return;

        LinkedList<TreeNode> list = new LinkedList<>();
        list.add(root);
        while(list.size() != 0) {
            TreeNode node = list.removeFirst();
            System.out.print(node.val + " ");
            if(node.left != null) {
                list.add(node.left);
            }
            if(node.right != null) {
                list.add(node.right);
            }
        }
        System.out.println();
    }

    public TreeNode invertTree(TreeNode root) {
        if(root == null) return null;
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        invertTree(root.left);
        invertTree(root.right);

        return root;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        solution.createTree();
        solution.levelTraverse(nodeList.get(0));
        TreeNode newRoot = solution.invertTree(nodeList.get(0));
        solution.levelTraverse(newRoot);
    }

}

最后输出的结果为:

1 2 3 4 5 6 7 8 9 
1 3 2 7 6 5 4 9 8 
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值