Last active
May 31, 2019 16:52
-
-
Save longfeixiang/eb7ec7d029be748f09bc935ede6510ad to your computer and use it in GitHub Desktop.
[检查二叉树是否存在一条路径] #编程题
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
// 问题:检查二叉树是否存在一条路径 | |
const hasPathSum = (root, sum) => { | |
// console.count('%s run', this.name) | |
if (!root || root.value > sum) { | |
return false | |
} else if (root.value === sum) { | |
return true | |
} | |
return hasPathSum(root.left, sum - root.value) || hasPathSum(root.right, sum - root.value) | |
} | |
const main = () => { | |
const tree = { | |
value: 5, | |
left: { | |
value: 4, | |
left: { | |
value: 11, | |
left: { | |
value: 7, | |
}, | |
right: { | |
value: 2, | |
} | |
}, | |
}, | |
right: { | |
value: 8, | |
left: { | |
value: 13, | |
}, | |
right: { | |
value: 4, | |
right: { | |
value: 1 | |
}, | |
}, | |
}, | |
} | |
console.assert(hasPathSum(tree, 123) === false) | |
console.assert(hasPathSum(tree, 22)) | |
} | |
// main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment