列印二叉樹兩個葉子節點間的路徑,二叉樹節點

來源:互聯網
上載者:User

列印二叉樹兩個葉子節點間的路徑,二叉樹節點
轉載請註明出處:http://blog.csdn.net/luonanqin



       前兩天在網上看到百度的一個校園招聘面試題:輸出二叉樹中兩個葉子節點間的路徑。感覺不是很難,所以花了點時間用Java實現了下。如果有更好的想法可以一起討論。(另一個面試題是求二叉樹中的最長路徑,即相距最遠的兩個葉子節點,由於網上有實現所以我就不放出來了。)


public class TwoLeafPath {// 臨時存放要用的兩個葉子節點public static Node2 leaf = null;// 表示已經找到葉子節點public static boolean find = false;// 實在沒有好辦法輸出一個非平衡非完全二叉樹,所以各位看官自己畫畫吧:Ppublic static Node2 generateTree() {Node2 root = new Node2(1);Node2 node2 = new Node2(2);Node2 node3 = new Node2(3);Node2 node4 = new Node2(4);Node2 node5 = new Node2(5);Node2 node6 = new Node2(6);Node2 node7 = new Node2(7);Node2 node8 = new Node2(8);Node2 node9 = new Node2(9);Node2 node10 = new Node2(10);Node2 node11 = new Node2(11);Node2 node12 = new Node2(12);root.setParentNode(null);root.setLeftNode(node2);root.setRightNode(node3);node2.setLeftNode(node4);node2.setRightNode(node5);node3.setLeftNode(node6);node4.setLeftNode(node7);node4.setRightNode(node8);node5.setRightNode(node9);node8.setLeftNode(node10);node9.setLeftNode(node11);node11.setRightNode(node12);return root;}// 以後序遍曆的方式最快找到葉子節點public static void findNode(Node2 root, int data) {// 如果找到葉子節點則停止遍曆if (!find) {if (root.getLeftNode() != null) {root.getLeftNode().setParentNode(root);findNode(root.getLeftNode(), data);}}// 如果找到葉子節點則停止遍曆if (!find) {if (root.getRightNode() != null) {root.getRightNode().setParentNode(root);findNode(root.getRightNode(), data);}}if (root.getData() == data) {leaf = root;find = true;return;} else {return;}}public static void printLeavesPath(Node2 leaf1, Node2 leaf2) {int leaf1Data = leaf1.getData();int leaf2Data = leaf2.getData();Deque<Integer> leaf1Path = new LinkedList<Integer>();Deque<Integer> leaf2Path = new LinkedList<Integer>();while (true) {leaf1Path.offerFirst(leaf1.getData());leaf1 = leaf1.getParentNode();if (leaf1 == null) {break;}}System.out.println("Leaf "+leaf1Data+" Path: " + leaf1Path);while (true) {leaf2Path.offerFirst(leaf2.getData());leaf2 = leaf2.getParentNode();if (leaf2 == null) {break;}}System.out.println("Leaf "+leaf2Data+" Path: " + leaf2Path);int temp = 0;// 比較兩個葉子節點的路徑。從根節點開始往下尋找,若發現節點不同,則說明兩條路徑從此節點分叉。即可輸出兩葉子節點間的路徑while (leaf1Path.peekFirst() == leaf2Path.peekFirst()) {temp = leaf1Path.pollFirst();leaf2Path.pollFirst();}// 順序輸出Iterator<Integer> leaf1Iter = leaf1Path.iterator();// 逆序輸出Iterator<Integer> leaf2Iter = leaf2Path.descendingIterator();StringBuffer result = new StringBuffer();while (leaf2Iter.hasNext()) {result.append(leaf2Iter.next() + ", ");}result.append(temp + ", ");while (leaf1Iter.hasNext()) {result.append(leaf1Iter.next() + ", ");}System.out.println("Leaf " + leaf1Data + " & Leaf " + leaf2Data + " Path: " + result.substring(0, result.length() - 2));}public static void main(String[] args) {Node2 root = generateTree();int data1 = 6;int data2 = 12;findNode(root, data1);find = false;Node2 leaf1 = leaf;findNode(root, data2);find = false;Node2 leaf2 = leaf;if (leaf1 == null) {System.out.println("Can't find leaf with " + data1);}if (leaf2 == null) {System.out.println("Can't find leaf with " + data2);}printLeavesPath(leaf1, leaf2);}}

關鍵代碼如上,其餘代碼可自行腦補,或者參考我的github: https://github.com/luonanqin/study/tree/master/Algorithm/src


中序遍曆地解二叉樹中從根到葉子結點的所有路徑

為什麼一定要用中序?? 我覺得先序的效率更高些,當然,如果一定用中序的話,換下下面遞迴函式中的相關語句的順序即可。
思路:當前節點是嗎?--〉不是:判斷左右子樹;若當前節點或左右子樹是:將當前節點插入鏈表。
(唯寫了功能實現部分)

struct BTree
{
int node;
BTree* pLeft;
BTree* pRight;
};

struct List // 這個鏈表的目的是記錄路徑節點,便於調用的函數通過一個鏈表頭指標來處理,你可以不用它,直接cout的
{
int node;
List* pNext;
};

bool IsPath(BTree* pRoot, List** pHead, int leaf)
{
List* pInsert=NULL;

if (pRoot->node==leaf)
{
*pHead=new List;
*pHead->node=leaf;
*pHead->pNext=NULL;

// 記錄節點
cout<<"->"<<leaf;

return true;
}

if (pRoot->pLeft)
{
if (IsPath(pRoot->pLeft, pHead, leaf))
{
pInsert=new List;
pInsert->node=pRoot->node;
pInsert->pNext=*pHead;
*pHead=pInsert;

// 記錄節點
cout<<"->"<<leaf;

return true;
}
}

if (pRoot->pRight)
{
if (IsPath(pRoot->pRight, pHead, leaf))
{
pInsert=new List;
pInsert->node=pRoot->node;
pInsert->pNext=*pHead;
*pHead=pInsert;

// 記錄節點
cout<<"->"<<leaf;

return true;
}
}

return false;
}

調用該函數:
設根節點為pTree; 鏈表頭指標為pHead=NULL;葉子節點為5,
調用:
IsPath(pTree, &pHead, 5);
if (pHead==NULL)
{
; // 無該葉子節點
}...餘下全文>>
 
二叉樹葉子節點

葉子結點就是後面沒有孩子的!
解這題要知道一個東西:在任意一顆二叉樹中,度為零的節點個數為a,度為2的節點為b,那麼a=b +1.
本題中;b=18,a=19,
本題答案就是:b*2+a=18*2+19
(我就不高興算了)(b*2的意思就是說度為2的有兩個葉子結點)
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.