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

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

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

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 the root of binary tree
     * @return int整型二维数组
     */
    public int[][] threeOrders (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();
            if (node != null)
            {
                list.add(node.val);
                stack.push(node.right);
                stack.push(node.left);
            }
        }
        int[] pre = new int[list.size()];
        for (int i = 0; i < pre.length; i++)
        {
            pre[i] = list.get(i);
        }
        list.clear();

        // 中序
        TreeNode curr = root;
        while (!stack.isEmpty() || curr != null)
        {
            if (curr == null)
            {
                curr = stack.pop();
                list.add(curr.val);
                curr = curr.right;
            }
            else
            {
                stack.push(curr);
                curr = curr.left;
            }
        }
        int[] mid = new int[list.size()];
        for (int i = 0; i < mid.length; i++)
        {
            mid[i] = list.get(i);
        }
        list.clear();

        // 后序
        stack.push(root);
        while (!stack.isEmpty())
        {
            TreeNode node = stack.pop();
            if (node != null)
            {
                list.add(node.val);
                stack.push(node.left);
                stack.push(node.right);
            }
        }
        int[] pos = new int[list.size()];
        for (int i = 0, j = pos.length - 1; i < pos.length; i++, j--)
        {
            pos[i] = list.get(j);
        }

        // output 
        int[][] ans = new int[3][];
        ans[0] = pre;
        ans[1] = mid;
        ans[2] = pos;
        return ans;
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-25 17:55
点赞 评论 收藏
分享
07-07 12:47
门头沟学院 Java
码农索隆:竟然还真有卡体检报告的
点赞 评论 收藏
分享
求offer的大角牛:简历写的第一乱,没有突出重点,第二项目太多太杂看不出来有啥核心技术,第三自我评价太多了,第四获得的荣誉没啥含金量,可以不写,反正问题不少
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务