文章目录
- 二叉树算法
- 二叉树左右变换数据
今天来和大家谈谈常用的二叉树算法
二叉树算法
二叉树左右变换数据
举个例子:
Java来实现二叉树算法,将一个二叉树左右倒置(左右孩子节点互换)如下图所示
实现的代码如下:以下定义的类是内部类
// 2. 讲一个做二叉树左右替换
// 1. 先给一个二叉树的内部类,类里面分出左右的对象的变量public static class Tree {private Object data;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;}// 给出左右的树private Tree left;private Tree right;// 构造方法public Tree(Object data, Tree left, Tree right) {this.data = data;this.left = left;this.right = right;}/*** 获取二叉树的深度* @param root root* @return int*/public static int getMaxDepth(Tree root) {if (root == null) return 0;// 需要递归获取深度return Math.max(getMaxDepth(root.left), getMaxDepth(root.right)) + 1;}/*** 二叉树的交换方法OK,经过验证* @param root Tree*/public static void swap(Tree root) {if (root == null) return;// 交换Tree tmp = root.left;root.left = root.right;root.right = tmp;// 递归交换swap(root.left);swap(root.right);}/*** 二叉树的左右交换* @param root*/public static void swapAgin(Tree root) {if (root == null) return;Stack<Tree> statck = new Stack<>();statck.push(root);while (!statck.isEmpty()) {Tree node = statck.pop();Tree tmp = node.left;node.left = node.right;node.right = tmp;if (node.left != null) {statck.push(node.left);}if (node.right != null) {statck.push(node.right);}}}public static void main(String[] args) {// 以下模拟的二叉树图片地址在此: https://img-blog.csdnimg.cn/1ae454d94ab04d8e8fb6f313248beb3a.pngTree left9 = new Tree(9, null, null);Tree right3 = new Tree(3, null, null);Tree right8 = new Tree(8, null, null);Tree left7 = new Tree(7, null, right8);Tree right11 = new Tree(11, left9, right3);Tree root5 = new Tree(5, left7, right11);System.out.println("原始的二叉树结果:" + root5);
// 交换swap(root5);
// swapAgin(root5);System.out.println("swap()方法交换之后的二叉树结构为:" + root5);}}