首页 > 代码库 > Flatten Binary Tree to Linked List
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
思路:该题本质上是二叉树的先序遍历。我们首先来看递归的解法,函数FlattenSub(node)对以node为根的树进行处理,同时返回先序序列的尾节点的指针:
1 class Solution { 2 public: 3 void flatten( TreeNode *root ) { 4 if( !root ) { return; } 5 FlattenSub( root ); 6 } 7 private: 8 TreeNode *FlattenSub( TreeNode *node ) { 9 if( node->left ) {10 TreeNode *left_last = FlattenSub( node->left );11 left_last->right = node->right;12 node->right = node->left;13 node->left = 0;14 return FlattenSub( left_last );15 }16 if( node->right ) { return FlattenSub( node->right ); }17 return node;18 }19 };
接下来再看迭代的解法,基本思想是将父节点的地址保存到其左子树最右侧节点(即先序遍历的尾节点)的右指针字段,这样在左子树处理完成之后,可以再次回到父节点以完成对右子树的处理。
1 class Solution { 2 public: 3 void flatten( TreeNode *root ) { 4 if( !root ) { return; } 5 while( root ) { 6 if( root->left ) { 7 TreeNode *node = root->left; 8 while( node->right && node->right != root ) { node = node->right; } 9 if( node->right == root ) {10 node->right = root->right;11 root->right = root->left;12 root->left = 0;13 } else {14 node->right = root;15 root = root->left;16 }17 }18 TreeNode *node = root;19 while( node->right && !node->right->left ) { node = node->right; }20 if( node->right && node->right->left == root ) {21 root = node->right;22 node->right = root->right;23 root->right = root->left;24 root->left = 0;25 } else {26 root = node->right;27 }28 }29 return;30 }31 };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。