Flatten Binary Tree to Linked List
來源:程序員人生 發布時間:2015-01-18 10:34:12 閱讀次數:4064次
本文是在學習中的總結,歡迎轉載但請注明出處:http://blog.csdn.net/pistolove/article/details/42744919
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/
2 5
/
3 4 6
The flattened tree should look like:
1
2
3
4
5
6
思路:
(1)題意為將給定的2叉樹轉化為“只有右孩子節點”的鏈表(樹)。
(2)由上圖可知,如果右子樹不為空,則右子樹最后肯定為左子樹最有1個靠右的孩子節點的右子樹,而左子樹最后成為整棵樹的右子樹。這樣,首先判斷左子樹是不是為空,不為空就尋覓到樹根的左孩子節點,然后尋覓該節點是不是有右孩子,如果有繼續尋覓,直到找到屬于葉子節點的右孩子,此時,該節點的右子樹“指向”當前樹的右子樹,并將當前左子樹變成樹根的右孩子,將整棵樹左孩子置為空。最后,根節點“指向”根節點的右孩子,繼續上述操作,直到整棵樹遍歷完即得到結果。
(3)希望本文對你有所幫助。
算法代碼實現以下:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public void flatten(TreeNode root) {
while (root != null) {
if (root.left != null) {
TreeNode pre = root.left;
while (pre.right != null)
pre = pre.right;
pre.right = root.right;
root.right = root.left;
root.left = null;
}
root = root.right;
}
}
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈