LeetCode 145. 二叉树的后序遍历(非递归实现 java)

给你一棵二叉树的根节点 root ,返回其节点值的 后序遍历 。

示例 1:


输入:root = [1,null,2,3]
输出:[3,2,1]
示例 2:

输入:root = []
输出:[]
示例 3:

输入:root = [1]
输出:[1]
 

提示:

树中节点的数目在范围 [0, 100] 内
-100 <= Node.val <= 100

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-postorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List postorderTraversal(TreeNode root) {
        Stack stack = new Stack<>();
        List ret = new ArrayList<>();
        TreeNode prev = null;
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.peek();
            if (top.right == null || prev == top.right) {
                stack.pop();
                ret.add(top.val);
                prev = top;
            } else {
                cur = top.right;
            }
        }
        return ret;
    }
}

你可能感兴趣的:(数据结构OJ,leetcode,数据结构,java)