給定一個(gè)二叉樹,原地將它展開為鏈表。
例如铣揉,給定二叉樹
展開后的結(jié)果為:
算法思想:
具體代碼:
/**
* 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:
void flatten(TreeNode* root) {
if(root==NULL) return;
while(root!=NULL){
TreeNode*p = root;
if(p->left){
p = p->left;
while(p->right!=NULL){p = p->right;}
p->right = root->right;
root->right = root->left;
root->left = nullptr;
}
root = root->right;
}
}
};