題目描述
輸入一顆二叉樹的跟節點和一個整數,打印出二叉樹中結點值的和爲輸入整數的所有路徑。路徑定義爲從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。(注意: 在返回值的list中,數組長度大的數組靠前)
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function FindPath(root, expectNumber)
{
// write code here
var result = [], path = [], cur = 0;
if(!root) return result;
dfs(root, path, result, cur, expectNumber);
return result;
}
//深度優先遍歷
function dfs(root, path, result, cur, exp){
cur += root.val;
path.push(root.val);
if(cur == exp && root.left == null && root.right == null){
result.push(path.slice(0));
}
if(root.left){
dfs(root.left, path, result, cur, exp);
}
if(root.right){
dfs(root.right, path, result, cur, exp);
}
//該路徑遍歷完畢,返回樹的上一層
path.pop();
}