【剑指offer】面试题34:二叉树中和为某一值的路径(Java)
輸入一棵二叉樹(shù)和一個(gè)整數(shù),打印出二叉樹(shù)中節(jié)點(diǎn)值的和為輸入整數(shù)的所有路徑。從樹(shù)的根節(jié)點(diǎn)開(kāi)始往下一直到葉節(jié)點(diǎn)所經(jīng)過(guò)的節(jié)點(diǎn)形成一條路徑。
?
示例:
給定如下二叉樹(shù),以及目標(biāo)和?sum = 22,
? ? ? ? ? ? ? 5
? ? ? ? ? ? ?/ \
? ? ? ? ? ? 4 ? 8
? ? ? ? ? ?/ ? / \
? ? ? ? ? 11 ?13 ?4
? ? ? ? ?/ ?\ ? ?/ \
? ? ? ? 7 ? ?2 ?5 ? 1
返回:
[
? ?[5,4,11,2],
? ?[5,8,4,5]
]
?
提示:
節(jié)點(diǎn)總數(shù) <= 10000
代碼:
/**
?*?Definition?for?a?binary?tree?node.
?*?public?class?TreeNode?{
?*?????int?val;
?*?????TreeNode?left;
?*?????TreeNode?right;
?*?????TreeNode(int?x)?{?val?=?x;?}
?*?}
?*/
class?Solution?{
?????List<List<Integer>>?result?=?new?LinkedList<List<Integer>>();
????public?List<List<Integer>>?pathSum(TreeNode?root,?int?sum)?{
????????if(root==null)
????????{
????????????return?result;
????????}
????????List<Integer>?list?=?new?LinkedList<Integer>();
????????find(list,root,0,sum);
????????return?result;
????}
????public?void?find(List<Integer>?list,TreeNode?root,int?target,int?sum)
????{
????????if(root==null)
????????{
????????????return;
????????}
????????target+=root.val;
????????list.add(root.val);
????????if(target==sum&&root.left==null&&root.right==null)
????????{
????????????result.add(new?LinkedList<>(list));
????????}
????????else
????????{
????????????find(list,root.left,target,sum);
????????????find(list,root.right,target,sum);
????????}
????????list.remove(list.size()-1);
????????
????}
}
總結(jié)
以上是生活随笔為你收集整理的【剑指offer】面试题34:二叉树中和为某一值的路径(Java)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【剑指offer】面试题68 - I:二
- 下一篇: Java中关于自增自减