Java交换二叉树的左右子树_二叉树左右子树交换

本文介绍了两种在Java中交换二叉树左右子树的方法:递归和使用栈。通过创建二叉树节点并调用相应方法,实现了交换操作,并在主函数中进行演示。
摘要由CSDN通过智能技术生成

1. 递归

2. 栈

package org.skyeye.test;

import java.util.Stack;

public class TreeSwap {

public static class Tree{

private Object data;

private Tree left;

private Tree right;

public Tree(Object data, Tree left, Tree right) {

this.data = data;

this.left = left;

this.right = right;

}

public Object getData() {

return data;

}

public void setData(Object data) {

this.data = data;

}

public Tree getLeft() {

return left;

}

public void setLeft(Tree left) {

this.left = left;

}

public Tree getRight() {

return right;

}

public void setRight(Tree right) {

this.right = right;

}

}

public static int getMaxDepth(Tree root) {

if(root==null) {

return 0;

}

return Math.max(getMaxDepth(root.left), getMaxDepth(root.right))+1;

}

public static void swap1(Tree root) {

if(root == null) {

return;

}

Tree tmp = root.left;

root.left = root.right;

root.right = tmp;

swap1(root.left);

swap1(root.right);

}

public static void swap2(Tree root) {

if(root==null) {

return;

}

Stack stack = new Stack();

stack.push(root);

while(!stack.empty()) {

Tree node = stack.pop();

Tree tmp = node.left;

node.left = node.right;

node.right = tmp;

if(node.left!=null) {

stack.push(node.left);

}

if(node.right!=null) {

stack.push(node.right);

}

}

}

public static void main(String[] args) {

Tree lll = new Tree(1, null, null);

Tree ll = new Tree(2, lll, null);

Tree lr = new Tree(3, null, null);

Tree l = new Tree(4, ll, lr);

Tree rl = new Tree(7, null, null);

Tree rr = new Tree(8, null, null);

Tree r = new Tree(6, rl, rr);

Tree root = new Tree(5, l, r);

swap2(root);

System.out.println(root);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值