二叉树左右子树交换

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<Tree> stack = new Stack<Tree>();
		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);
	}
}

  

猜你喜欢

转载自www.cnblogs.com/lowseasonwind/p/9083250.html