114. Flatten Binary Tree to Linked List
1.問題
給予一個binary tree, 將他攤平成linked list (in-place)

2.想法
提問
確認題意: root是NULL是true或false?
function header, parameter
test input
說明想法
1.用pre-order traversal整個tree, 用指標調整: 將下個node放到right
測試計算複雜度
3.程式碼
pre-order traversal
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* tmp = NULL;
void flatten(TreeNode* root) {
if (!root) {
return;
}
if (tmp) {
//將tmp的right child指向下個root
tmp->left = NULL;
tmp->right = root;
}
//將tmp指向下個root(移動)
tmp = root;
//儲存right
TreeNode *right = root->right;
//先整理left
flatten(root->left);
//整理right
flatten(right);
}
};
Last updated