日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

IT公司100题-4-在二元树中找出和为某一值的所有路径

發布時間:2025/7/14 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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-在二元树中找出和为某一值的所有路径的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。