深度優(yōu)先和廣度優(yōu)先

路徑總和

是否存在從當(dāng)前節(jié)點 root 到葉子節(jié)點的路徑,滿足其路徑和為 sum
let root = {value: 5,left: {value: 4,left: {value: 11,left: {value: 7,left: null,right: null},right: {value: 2,left: null,right: null}},right: null},right: {value: 8,left: {value: 13,left: null,right: null},right: {value: 4,left: null,right: {value: 1,left: null,right: null}}}}
假定從根節(jié)點到當(dāng)前節(jié)點的值之和為 val,我們可以將這個大問題轉(zhuǎn)化為一個小問題:是否存在從當(dāng)前節(jié)點的子節(jié)點到葉子的路徑,滿足其路徑和為 sum - val。
// 深度優(yōu)先function hasPathSum (root, sum) {if (root == null) {return false}if (root.left == null && root.right == null) {return root.value === sum}return hasPathSum(root.left, sum - root.value) || hasPathSum(root.right, sum - root.value)}
廣度優(yōu)先
// 廣度優(yōu)先function hasPathSum (root, sum) {if (root === null) {return false}let node = [root]let value = [root.value]while (node.length) {let now = node.shift()let temp = value.shift()if (temp === sum) {return true}if (now.left && now.left !== null) {node.push(now.left)value.push(now.left.value + temp)}if (now.right && now.right !== null) {node.push(now.right)value.push(now.right.value + temp)}}return false}
我們再看一個面試題,計算二叉樹的所有路徑。
// 深度優(yōu)先function binaryTree (root) {let paths = []let construct_paths = (root, path) => {if (root) {path += root.value.toString()if (root.left === null && root.right === null) {paths.push(path)} else {// 當(dāng)前節(jié)點不是葉子節(jié)點,繼續(xù)遞歸path += '->'construct_paths(root.left, path)construct_paths(root.right, path)}}}construct_paths(root, '')return paths}// [ '5->4->11->7', '5->4->11->2', '5->8->13', '5->8->4->1' ]
廣度優(yōu)先
// 廣度優(yōu)先function binaryTree (root) {if (root === null) {return false}let node = [root]let value = [root.value]let paths = []while (node.length) {let now = node.shift()let temp = value.shift()if (now.left === null && now.right === null) {paths.push(temp)}if (now.left && now.left !== null) {node.push(now.left)value.push(temp + '->'+ now.left.value)}if (now.right && now.right !== null) {node.push(now.right)value.push(temp + '->'+ now.right.value)}}return paths}
這里在提一句,深度優(yōu)先和廣度優(yōu)先的感念, “深度優(yōu)先搜索就是樹的先序遍歷”,“廣度優(yōu)先搜索就是樹的按層遍歷”。
評論
圖片
表情
