Skip to content

Instantly share code, notes, and snippets.

@marklin-latte
Last active January 7, 2018 08:44
Show Gist options
  • Save marklin-latte/b61e85f3495e723dd3ced4f925409861 to your computer and use it in GitHub Desktop.
Save marklin-latte/b61e85f3495e723dd3ced4f925409861 to your computer and use it in GitHub Desktop.
#257 Binary Tree Paths
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {string[]}
*/
var binaryTreePaths = function(root) {
// 1. traveling the all node with pre order.
// 2. save the node path.
// 3. when traveling to the bottom node , pushing the path to result.
let stack = [];
let current;
let result =[];
if(!root){
return [];
}
stack.push({
node: root,
path: root.val + ""
});
while (stack.length > 0){
current = stack.pop();
if(current.node.left === null && current.node.right === null){
result.push(current.path);
}
if(current.node.right){
stack.push({
node: current.node.right,
path: current.path + "->" + current.node.right.val
});
}
if(current.node.left){
stack.push({
node: current.node.left,
path: current.path + "->" + current.node.left.val
});
}
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment