Skip to content

Instantly share code, notes, and snippets.

@mvalipour
Created December 5, 2016 23:38
Show Gist options
  • Save mvalipour/954cf5ccc210d827d441808db7fd48cc to your computer and use it in GitHub Desktop.
Save mvalipour/954cf5ccc210d827d441808db7fd48cc to your computer and use it in GitHub Desktop.
postorderTraversal
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var postorderTraversal = function(root) {
var stack = root ? [root] : [];
var prev = null;
var res = [];
while(stack.length > 0) {
var node = stack.pop();
var visit = node;
if(!node.left) {
visit = prev === node.right ? node : node.right;
}
else if(!prev || prev !== node.right){
visit = prev === node.left ? node.right : node.left;
}
if(visit && visit !== node) {
stack.push(node);
stack.push(visit);
}
else {
res.push(node.val);
}
prev = node;
}
return res;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment