美文网首页算法代码
二叉树的中序遍历

二叉树的中序遍历

作者: windUtterance | 来源:发表于2020-06-02 09:50 被阅读0次

题目描述
给定一个二叉树,返回它的中序 遍历。

示例
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]

核心思想如下:
1.使用颜色标记节点的状态:新节点为白色,访问过的节点为灰色
2.如果遇到的节点为白色,则将其标记为灰色,然后将其右子节点,自身,左子节点依次入栈
3.如果遇到的节点为灰色,则将节点的值输出

Java代码

/**
 * 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 cn = stack.pop();

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

相关文章

网友评论

    本文标题:二叉树的中序遍历

    本文链接:https://www.haomeiwen.com/subject/snpyzhtx.html