码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 145. Binary Tree Postorder Traversal

时间:2019-04-14 20:38:47      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:public   ...   nta   array   -o   art   empty   hash   tor   

I never tried before to implement postorder traversal of binary tree with non-recursive method.
So the ugly handwork is attached below.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        Stack<TreeNode> s = new Stack<>();
        Set<TreeNode> poped = new HashSet<>();
        TreeNode node = root;
        while (node != null || !s.isEmpty()) {
            while (node != null) {
                s.add(node);
                node = node.left;
            }
            node = s.pop();
            if (poped.contains(node)) {
                ret.add(node.val);
                node = null;
            }
            else {
                poped.add(node);
                s.add(node);
                node = node.right;
            }
        }
        return ret;
    }
}

But In the discuss area, I saw a much better version for pre-order, in-order and post-order non-recursive implementation.
I‘ll write an article, the link is.... [TO DO ]

leetcode 145. Binary Tree Postorder Traversal

标签:public   ...   nta   array   -o   art   empty   hash   tor   

原文地址:https://www.cnblogs.com/exhausttolive/p/10706829.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!