Last active
January 7, 2018 08:44
-
-
Save marklin-latte/b61e85f3495e723dd3ced4f925409861 to your computer and use it in GitHub Desktop.
#257 Binary Tree Paths
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 {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