二叉树的三种遍历方法

二叉树的序列化

为了方便构造二叉树来验证我们的算法,这里先介绍下二叉树的序列化和反序列化。

序列化

先序遍历整颗二叉树即可,碰到节点存储下来,逗号隔开,若是空节点则记为#

代码如下:

public static String serialize(TreeNode root) {
    StringBuilder sb = new StringBuilder();
    sb.append('[');
    serialize(root, sb);
    sb.deleteCharAt(sb.length() - 1);
    sb.append(']');
    return sb.toString();
}



private static void serialize(TreeNode root, StringBuilder sb) {
    if (root == null) {
        sb.append('#');
        sb.append(',');
    } else {
        sb.append(root.val);
        sb.append(',');
        serialize(root.left, sb);
        serialize(root.right, sb);
    }
}

反序列化

和序列化思路一致,先构造根节点,依次构造树的左子树、右子树。

因为int是栈空间的变量,而Integer是不可变类,我们这里构造一个包装类IntegerHolder传递不停自增的数组下标。

代码如下:

public static TreeNode deserialize(String str) {
    str = str.substring(1, str.length() - 1);
    if (str.isEmpty()) return null;
    String[] nums = str.split(",");
    return deserialize(nums, new IntegerHolder());
}

private static TreeNode deserialize(String[] nums, IntegerHolder integerHolder) {
    if (nums.length <= integerHolder.index) return null;
    if (nums[integerHolder.index].equals("#")) {
        integerHolder.index++;
        return null;
    }
    TreeNode root = new TreeNode(Integer.parseInt(nums[integerHolder.index++]));
    root.left = deserialize(nums, integerHolder);
    root.right = deserialize(nums, integerHolder);
    return root;
}

private static class IntegerHolder {
    int index = 0;
}

二叉树的三种遍历

先序遍历(PreOrder)

递归方法

public void preOrder(TreeNode root) {
    if (root == null) return;
    System.out.print(root.val + " ");
    preOrder(root.left);
    preOrder(root.right);
}

迭代方法

public void preOrder(TreeNode root) {
    if (root == null) return;
    Stack<TreeNode> st = new Stack<>();
    TreeNode node = root;
    while (!st.empty() || node != null) {
        if (node == null) {
            node = st.pop();
        } else {
            System.out.print(node.val + " ");
            if (node.right != null) st.push(node.right);
            node = node.left;
        }
    }
}

中序遍历(InOrder)

递归方法

public void inOrder(TreeNode root) {
    if (root == null) return;
    inOrder(root.left);
    System.out.print(root.val + " ");
    inOrder(root.right);
}

迭代方法

public void inOrder(TreeNode root) {
    if (root == null) return;
    Stack<TreeNode> st = new Stack<>();
    TreeNode node = root;
    while (!st.empty() || node != null) {
        if (node == null) {
            node = st.pop();
            System.out.print(node.val + " ");
            node = node.right;
        } else {
            st.push(node);
            node = node.left;
        }
    }
}

后序遍历(PostOrder)

递归方法

public void postOrder(TreeNode root) {
    if (root == null) return;
    postOrder(root.left);
    postOrder(root.right);
    System.out.print(root.val + " ");
}

迭代方法

public void postOrder(TreeNode root) {
    if (root == null) return;
    Stack<TreeNode> st = new Stack<>();
    List<Integer> list = new ArrayList<>();
    TreeNode node = root;
    while (!st.empty() || node != null) {
        if (node == null) {
            node = st.pop();
        } else {
            list.add(node.val);
            if (node.left != null) st.push(node.left);
            node = node.right;
        }
    }
    Collections.reverse(list);
    for (int i : list) System.out.print(i + " ");
}
    原文作者:九命丿相柳
    原文地址: https://www.jianshu.com/p/358d8cbe4c07
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞