二叉树的反转,递归实现和非递归实现。

来源:互联网 发布:linux 红底白字 编辑:程序博客网 时间:2024/04/30 05:52
package com.alg;import java.util.Stack;/** * Created by lchli on 2016/3/5. */public class BTreeRevert {    public static class Node {        public Node left;        public Node right;        public Object data;    }    /**     * 递归实现。     *     * @param root     */    public static void recusiveRevert(Node root) {        if (root == null) {            return;        }        swap(root);        recusiveRevert(root.left);        recusiveRevert(root.right);    }    /**     * 非递归实现。     *     * @param root     */    public static void stackRevert(Node root) {        if (root == null) {            return;        }        Stack<Node> stack = new Stack<>();        stack.push(root);        while (!stack.isEmpty()) {            Node current = stack.pop();            swap(current);            if (current.left != null) {                stack.push(current.left);            }            if (current.right != null) {                stack.push(current.right);            }        }    }    private static void swap(Node root) {        Node tmp = root.left;        root.left = root.right;        root.right = tmp;    }    /**     * test.前序输出。     *     * @param root     */    public static void preorderOutput(Node root) {        if (root == null) {            return;        }        System.out.print(root.data);        preorderOutput(root.left);        preorderOutput(root.right);    }}

0 0
原创粉丝点击