题解 | #实现二叉树先序,中序和后序遍历#

实现二叉树先序,中序和后序遍历

http://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362

非递归,利用栈实现

public int[][] threeOrders(TreeNode root) {
        int[][] result = new int[3][];
        result[0] = preSort(root);
        result[1] = inSort(root);
        result[2] = postSort(root);
        return result;
    }

    public int[] transformArr(List<Integer> list) {
        if (list == null || list.isEmpty()) {
            return null;
        }
        int[] arr = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            arr[i] = list.get(i);
        }
        return arr;
    }

    public int[] preSort(TreeNode root) {
        if (root == null) {
            return null;
        }
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            list.add(node.val);
            if (node.right != null) {
                stack.push(node.right);
            }
            if (node.left != null) {
                stack.push(node.left);
            }
        }
        return transformArr(list);
    }

    public int[] inSort(TreeNode root) {
        if (root == null) {
            return null;
        }
        List<Integer> list = new ArrayList<>();
        Stack<Object> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            Object element = stack.pop();
            if (element instanceof TreeNode) {
                TreeNode node = (TreeNode) element;
                if (node.right != null) {
                    stack.push(node.right);
                }
                stack.push(node.val);
                if (node.left != null) {
                    stack.push(node.left);
                }
            } else {
                list.add(((Integer) element));
            }
        }
        return transformArr(list);
    }

    public int[] postSort(TreeNode root) {
        if (root == null) {
            return null;
        }
        List<Integer> list = new ArrayList<>();
        Stack<Object> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            Object element = stack.pop();
            if (element instanceof TreeNode) {
                TreeNode node = (TreeNode) element;
                stack.push(node.val);
                if (node.right != null) {
                    stack.push(node.right);
                }
                if (node.left != null) {
                    stack.push(node.left);
                }
            } else {
                list.add(((Integer) element));
            }
        }
        return transformArr(list);
    }
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务