😋 将左子树插入到右子树上
java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public void flatten(TreeNode root)
{
while (root != null)
{
if (root.left == null)// 找到具有左节点的树
root = root.right;
else
{
TreeNode pre = root.left;// 当前左子树的先序遍历序列的最后一个结点
while (pre.right != null)
pre = pre.right;
pre.right = root.right;// 将当前右子树接在左子树的最右结点的右孩子上
root.right = root.left;// 左子树插入当前树的右子树的位置上
root.left = null;
root = root.right;// 递归处理每一个拥有左子树的结点
}
}
}
}
😋 递归
null<-6<-5<-4<-3<-2<-1
java
class Solution {
public void flatten(TreeNode root) {
helper(root);
}
TreeNode pre = null;
void helper(TreeNode root) {
if(root==null) {
return;
}
//右节点-左节点-根节点 这种顺序正好跟前序遍历相反
//用pre节点作为媒介,将遍历到的节点前后串联起来
helper(root.right);
helper(root.left);
root.left = null;
root.right = pre;
pre = root;
}
}