文章目錄
- 二叉樹算法
- 二叉樹左右變換數據
今天來和大家談談常用的二叉樹算法
二叉樹算法
二叉樹左右變換數據
舉個例子:
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);}}