題目
將一棵二叉樹按照前序遍歷拆解成為一個假鏈表
。所謂的假鏈表是說,用二叉樹的 right 指針,來表示鏈表中的 next 指針。
注意事項
不要忘記將左兒子標記為 null,否則你可能會得到空間溢出或是時間溢出。
樣例
1
\
1 2
/ \ \
2 5 => 3
/ \ \ \
3 4 6 4
\
5
\
6
解題
修改前序遍歷
/** * 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 * 前序遍歷:根左右 * 修改根的right指向左部分 * 左部分的right指向右部分 */ public void flatten(TreeNode root) { // write your code here // 空結點 if(root == null) return; // 左右結點都空 if(root.left==null && root.right==null) return; // 左結點空 if(root.left==null){ TreeNode right = root.right; flatten(right); return; } // 右節點空 if(root.right==null){ TreeNode left = root.left; root.right = left; flatten(left); root.left = null;// left結點設置為空 return; } // 左右結點都不空 TreeNode left = root.left; TreeNode right = root.right; root.right = left; flatten(left); TreeNode p = left; while(p.right!=null){ // 找到left部分的最右結點 p = p.right; } p.right = right; flatten(right); root.left = null; // left結點設置為空 return; } }