👨🏫 题目地址
👩🏫 参考题解
😋 将左子树插入到右子树上
/*** 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
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;}
}