My accepted code java re-preOrder


  • 0
    C

    re-preOrder: node->node.right->node.left

    postOrder: node.left->node.right->node

      public List<Integer> postorderTraversal(TreeNode root) {
            List<Integer> res = new ArrayList<Integer>();
            if(root==null)
                return res;
            Stack<TreeNode> stack = new Stack<TreeNode>();
            stack.push(root);
            // root->right->left
            while(!stack.isEmpty()) {
                TreeNode node = stack.pop();
                res.add(node.val);
                if(node.left!=null) {
                    stack.push(node.left);
                }
                if(node.right!=null) {
                    stack.push(node.right);
                }            
            }
            int len = res.size();
            for(int i=0;i<len/2;i++) {
                int t = res.get(i);
                res.set(i, res.get(len-1-i));            
                res.set(len-1-i, t);
            }
            return res;
       }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.