114. 二叉树展开为链表
解题思路
用后序遍历,把左子树接到根节点上,再把原来的右子树接到现在的右子树上,然后把原来的左子树置为null。 虽然是后序遍历,但是连接起来成链表,就是前序遍历的结果
代码
/**
* 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 temp = root.right;
//把树的右边换成左边的节点
root.right = root.left;
//记得要将左边置空
root.left = null;
//找到树的最右边的节点
while(root.right != null) root = root.right;
//把右边的节点接到现在树的最右边的节点
root.right = temp;
}
}