問題描述:
將一棵二叉樹按照前序遍歷拆解成爲一個假鏈表
。所謂的假鏈表是說,用二叉樹的 right 指針,來表示鏈表中的 next 指針。
注意事項
不要忘記將左兒子標記爲 null,否則你可能會得到空間溢出或是時間溢出
樣例
1
\
1 2
/ \ \
2 5 => 3
/ \ \ \
3 4 6 4
\
5
\
6
解題思路:
將右子樹放在左子樹後面,然後將右子樹重新賦值成左子樹,將左子樹變成空。
代碼:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
void flatten(TreeNode *root) {
if (root == NULL) return;
while (root!=NULL) {
if (root->left!=NULL) {
TreeNode *p = root->left;
while (p->right!=NULL)
p = p->right;
p->right = root->right;
root->right = root->left;
root->left = NULL;
}
root = root->right;
}
// write your code here
}
};
感想:
解法並不唯一,變通