java 将树的左右对换_[Java]将二叉树的左右子树交换 非递归实现

该博客介绍了如何使用非递归方式交换二叉树的左右子树。通过创建一个Stack并遍历节点,当遇到未访问的节点时,先将其压入栈中,然后交换左右子树。提供了完整的Java代码实现,包括构建树、中序遍历和交换子树的方法。
摘要由CSDN通过智能技术生成

package dataStruct;

import java.util.Stack;

/**

* 将二叉树的左右子树交换 非递归实现

* @author YangYi

*/

public class SwapTree {

private static Stack stack = new Stack();

public static void main(String args[]) {

Node root = buildTree();

inOrderVisit(root);

swapTree(root);

System.out.println();

inOrderVisit(root);

}

public static void inOrderVisit(Node root) {

if (root == null)

return;

inOrderVisit(root.left);

System.out.print(root.data);

inOrderVisit(root.right);

}

public static void swapTree(Node root) {

if (root == null)

return;

Node temp = null;

stack.push(root);

while (!stack.isEmpty()) {

Node node = stack.peek();

if (node.left == null && node.right == null) {

node.visited = true;

stack.pop();

continue;

}

if (node.left != null) {

if (!node.left.visited) {

stack.push(node.left);

}

}

if ((node.left == null || node.left.visited) && node.right != null) {

if (!node.right.visited) {

stack.push(node.right);

}

}

if ((node.left == null || node.left.visited)

&& (node.right == null || node.right.visited)) {

temp = node.left;

node.left = node.right;

node.right = temp;

node.visited = true;

stack.pop();

}

}

}

public static Node buildTree() {

Node root = new Node();

root.data = 1;

Node temp = new Node();

temp.data = 2;

root.left = temp;

temp = new Node();

temp.data = 3;

root.right = temp;

temp = new Node();

temp.data = 4;

root.right.right = temp;

temp = new Node();

temp.data = 5;

root.left.right = temp;

temp = new Node();

temp.data = 6;

root.left.right.right = temp;

return root;

}

}

class Node {

boolean visited = false;

int data = 0;

Node left = null;

Node right = null;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值