二叉树篇。
/**
* 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 {
//1.将传入的树转为右斜线树
public void flatten(TreeNode root) {
//2.极小
if(root==null){
return;
}
if(root.left==null&&root.right==null){
return;
}
//3.极大
//3.1
if(root.left==null){
flatten(root.right);
return;
}
//3.2
else{
//3.2.1 变为线型
flatten(root.left);
flatten(root.right);
//3.2.2 右子树拼到左子树右下角
TreeNode temp=root.left;
while(temp.right!=null){
temp=temp.right;
}
temp.right=root.right;
//3.2.3 左子树移到右边变为root右子树
root.right=root.left;
//3.2.4 root左子树变为null
root.left=null;
return;
}
}
}
过关斩将,easy!