/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public void flatten(TreeNode root) {
aidFlatten(root);
}
private TreeNode aidFlatten(TreeNode root) {
if (root==null)
return null;
TreeNode right = root.right;
TreeNode f1 = aidFlatten(root.left);
root.left = null;
root.right = f1;
while (f1 != null && f1.right != null) {
f1 = f1.right;
}
if (f1!=null){
f1.right = aidFlatten(right);
}else {
root.right = aidFlatten(right);
}
return root;
}
}
写递归时,要把递归函数看作是一个黑盒,不要管在每一次递归分支如何实现,比如在该题中,只需要知道,他可以实现这个功能就可以了,只需要写好当前节点的各种情况处理。