1 classSolution {2 Public:3 voidFlatten (treenode*root) {4 if(!root)return;5Flatten (root->Left );6Flatten (root->Right );7 8treenode* right = root->Right ;9Root->right = root->Left ;TenRoot->left =NULL; One while(root->Right ) { Aroot = root->Right ; - } -Root->left =NULL; theRoot->right =Right ; - } -};
Originally thought that the last flatten of the tree must be in order to small to large, so as to
3
1 4
2 5
The left side of the tree is 1-2-5, and the right side is flatten to insert the left subtree. Later found to think more, only need all the nodes have no left subtree, but still to follow a certain order.
Test instructions still very clear, leave the pit.
The order of the topics required is the pre-order, i.e. root-root->left-root->right.
Enter the tree above:
Your input
[3,1,4,2,5]
Your Answer
[3,null,1,null,2,null,5,null,4]
Expected answer
[3,null,1,null,2,null,5,null,4] That is, indeed, the pre-order.
There are other algorithms, not seen, left pits.
Leetcode 114. Flatten Binary Tree to Linked List