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

二叉树的后序遍历

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

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

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

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> postorderTraversal(TreeNode root) {
        if(root == null) return new ArrayList<>();
        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")) {
                stack.push(new ColorNode(cn.node, "gray"));
                if(cn.node.right != null) stack.push(new ColorNode(cn.node.right, "white"));
                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/wjcvzhtx.html