欢迎大家阅读参考,如有错误或疑问请留言纠正,谢谢
114 Flatten Binary Tree to Linked List
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* flattenUtil(TreeNode *root) { if( root==NULL ) return NULL; TreeNode *left = root->left; TreeNode *right = root->right; root->left = NULL; if(left) { root->right = left; root = flattenUtil(left); //root指针指向left,即next } if(right) { root->right = right; root = flattenUtil(right); //root指针指向right,即next } return root; } void flatten(TreeNode *root) { flattenUtil(root); } };
时间: 2025-01-06 03:24:42