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
将一颗二叉树转化为链表,right充当next指针,元素顺序为先序遍历的循序。不使用额外的空间
/** * 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* flattenTree(TreeNode *root){ if(root->left==NULL && root->right==NULL)return root; TreeNode*tail=root; TreeNode*headLeft=root->left; TreeNode*tailLeft=NULL; TreeNode*headRight=root->right; TreeNode*tailRight=NULL; //【注意】左孩子清NULL root->left=NULL; //将左子树链表化 if(headLeft!=NULL){ tailLeft=flattenTree(headLeft); tail->right=headLeft; tail=tailLeft; } //将右子树链表化 if(headRight!=NULL){ tailRight=flattenTree(headRight); tail->right=headRight; tail=tailRight; } return tail; } void flatten(TreeNode *root) { if(root==NULL)return; flattenTree(root); } };
LeetCode: Flatten Binary Tree to Linked List [114],布布扣,bubuko.com
LeetCode: Flatten Binary Tree to Linked List [114]
原文:http://blog.csdn.net/harryhuang1990/article/details/28587927