Created
December 5, 2016 23:38
-
-
Save mvalipour/954cf5ccc210d827d441808db7fd48cc to your computer and use it in GitHub Desktop.
postorderTraversal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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