仅供自己学习
思路:
题目要求最终的链表是按先序遍历的顺序排序,那么下意识会想到对左子树DFS直到没有左子树。再将该节点的左子树放到该节点右子树位置,再将原右子树放到新右子树的右子树位置即可。
代码
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class Solution { 13 public: 14 void flatten(TreeNode* root) { 15 if(root==NULL ||!root->left&&!root->right) return ; //因为此方法会对叶子节点进行,但没必要,所以加此条件去除操作叶子节点 16 if(root->left)flatten(root->left); 17 if(root->right)flatten(root->right); 18 TreeNode* temp = root->right; 19 root->right=root->left; 20 root->left=NULL; 21 while(root->right) root=root->right; //当新右子树很多结点时就需要循环到最后的一个右子树,再连接上去 22 root->right= temp; 23 24 } 25 };
114. Flatten Binary Tree to Linked List
原文:https://www.cnblogs.com/Mrsdwang/p/14375704.html