leetcode94. 二叉树的中序遍历

。_饼干妹妹 提交于 2020-03-06 01:11:52
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {

    class ColorNode {
        TreeNode node;
        String color;

        public ColorNode(TreeNode node, String color) {
            this.node = node;
            this.color = color;
        }
    }

    public List<Integer> inorderTraversal(TreeNode root) {
        if (root == null) return new ArrayList<Integer>();

        List<Integer> res = new ArrayList<>();
        Stack<ColorNode> stack = new Stack<>();
        stack.push(new ColorNode(root, "white"));

        while (!stack.empty()) {
            ColorNode curr = stack.pop();
            if (curr.color.equals("white")) {
                if (curr.node.right != null) 
                    stack.push(new ColorNode(curr.node.right, "white"));
                stack.push(new ColorNode(curr.node, "gray"));
                if (curr.node.left != null) 
                    stack.push(new ColorNode(curr.node.left, "white"));
            } else {
                res.add(curr.node.val);
            }
        }
        return res;
    }
}

加粗样式

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!