二叉树展开为链表
题目:
给定一个二叉树,原地将它展开为一个单链表。
例如,给定二叉树
将其展开为:
解题思路:运用前序遍历将节点添加进list中,然后遍历list改变每一个节点的左右节点
/**
* 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 {
private List<TreeNode> list = new ArrayList();
public void flatten(TreeNode root) {
if(root == null)
return;
preOrder(root);
int len = list.size();
for(int i = 1; i < len; i++) {
TreeNode cur = list.get(i);
TreeNode pre = list.get(i - 1);
pre.left = null;
pre.right = cur;
}
}
private void preOrder(TreeNode node) {
if(node == null)
return ;
list.add(node);
preOrder(node.left);
preOrder(node.right);
}
}