描述
將一棵二叉樹按照前序遍歷拆解成為一個(gè)假鏈表。所謂的假鏈表是說,用二叉樹的 right 指針,來表示鏈表中的 next 指針。
注意事項(xiàng)
不要忘記將左兒子標(biāo)記為 null,否則你可能會(huì)得到空間溢出或是時(shí)間溢出。
樣例
1
\
1 2
/ \ \
2 5 => 3
/ \ \ \
3 4 6 4
\
5
\
6
標(biāo)簽
二叉樹&深度優(yōu)先搜索
相關(guān)題目
Flattern 2D Vector & 攤平嵌套的鏈表 &將二叉樹按照層級(jí)轉(zhuǎn)換為鏈表 &
將二叉查找樹轉(zhuǎn)換為雙鏈表&排序鏈表轉(zhuǎn)換為二叉樹
代碼實(shí)現(xiàn)
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
public void flatten(TreeNode root) {
helper(root);
}
// flatten root and return the last node
private TreeNode helper(TreeNode root) {
if (root == null) {
return root;
}
TreeNode leftLast = helper(root.left);
TreeNode rightLast = helper(root.right);
// connect leftLast to root.right
//root.right 接到leftLast的右子樹
//root.left置null
if (leftLast != null) {
leftLast.right = root.right;
root.right = root.left;
root.left = null;
}
//返回新鏈表的最后一個(gè)節(jié)點(diǎn)
//因?yàn)槭乔靶虮闅v,必然先判斷右子樹,再左子樹,最后根節(jié)點(diǎn)
if (rightLast != null) {
return rightLast;
}
if (leftLast != null) {
return leftLast;
}
return root;
}
}