题目:
思路一:通过先序遍历将元素放到一个数组中,再去遍历数组同时构造一棵二叉树。
代码略
思路二:先递归地把左子树展开为一个链表,再记录一下右子树,左子树移到右子树位置,把记录的右子树放到左子树右节点。
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) {
if(root == null){
return;
}
flatten(root.left);
flatten(root.right);
TreeNode trmp = root.right;
root.right = root.left;
root.left = null;
TreeNode cur = root;
while(cur != null){
if( cur.right == null){
cur.right = trmp;
break;
}
cur = cur.right;
}
return;
}
}