IT公司100题-4-在二元树中找出和为某一值的所有路径
生活随笔
收集整理的這篇文章主要介紹了
IT公司100题-4-在二元树中找出和为某一值的所有路径
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
問題描述:
輸入一個整數和一棵二元樹。從樹的根結點開始往下訪問一直到葉結點所經過的所有結點形成一條路徑。打印出和與輸入整數相等的所有路徑。
例如輸入整數30和如下二元樹
?
14
/ \
5?16
/ \
3?11
則打印出兩條路徑:14, 16 和14, 5, 11。
二元樹節點的數據結構定義為:
class?BSTreeNode{BSTreeNode(int?x,?BSTreeNode?lt,?BSTreeNode?rt){value?=?x;left?=?lt;right?=?rt;}int?value;BSTreeNode?left;BSTreeNode?right;}在遍歷樹的過程中,使用stack保存所走過的路徑。如果當前節點為葉子節點,并且路徑和等于輸入的整數,則輸出路徑。如果當前節點不是葉子節點,則遞歸的訪問它的孩子節點。在回溯的過程中,注意路徑的出棧。
代碼實現:
package?oschina.mianshi; /***?@project:?oschina*?@filename:?IT3.java*?@version:?0.10*?@author:?JM?Han*?@date:?14:59?2015/10/22*?@comment:?Test?Purpose*?@result:*/import?java.util.Stack;import?static?tool.util.*;class?BSTree3{class?BSTreeNode{BSTreeNode(int?x,?BSTreeNode?lt,?BSTreeNode?rt){value?=?x;left?=?lt;right?=?rt;}int?value;BSTreeNode?left;BSTreeNode?right;}private?BSTreeNode?root;private?int?currentSum;private?Stack<Integer>?path;public?BSTree3(){root?=?null;currentSum?=?0;path?=?new?Stack<Integer>();}public?void?insert(int?value){root?=?insert(root,?value);}private?BSTreeNode?insert(BSTreeNode?t,?int?x){if(null?==?t)return?new?BSTreeNode(x,?null,?null);if(t.value?>?x)t.left?=?insert(t.left,?x);else?if(t.value?<?x)t.right?=?insert(t.right,?x);else;//duplicatereturn?t;}public?void?findPath(int?expectSum){findPath(root,?expectSum);}private?void?findPath(BSTreeNode?t,?int?expectSum){if(null?==?t)return;currentSum?+=?t.value;path.push(t.value);boolean?isLeaf?=?(t.left?==?null?&&?t.right?==?null);if(isLeaf?&&?currentSum?==?expectSum){printGenericColection(path);}if(null?!=?t.left)findPath(t.left,?expectSum);if(null?!=?t.right)findPath(t.right,?expectSum);currentSum?-=?t.value;path.pop();} }public?class?IT3?{public?static?void?main(String[]?args)?{BSTree3?bsTree?=?new?BSTree3();bsTree.insert(14);bsTree.insert(5);bsTree.insert(16);bsTree.insert(3);bsTree.insert(11);bsTree.findPath(30);} }代碼輸出:
14 5 11 14 16轉載于:https://my.oschina.net/jimmyhan/blog/520689
總結
以上是生活随笔為你收集整理的IT公司100题-4-在二元树中找出和为某一值的所有路径的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: cocos2dx 大地图分块加载的研究(
- 下一篇: JDBC的复习