二叉树展开为链表
题目描述:
给你二叉树的根结点 root ,请你将它展开为一个单链表:展开后的单链表应该同样使用 TreeNode ,其中 right 子指针指向链表中下一个结点,而左子指针始终为 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 {
private Queue<TreeNode> queue = new LinkedList<TreeNode>();
public void flatten(TreeNode root) {
if(root == null) return;
helper(root);
TreeNode temp = queue.poll();
while(!queue.isEmpty()){
temp.right = queue.poll();
temp.left = null;
temp = temp.right;
}
}
private void helper(TreeNode root){
if(root == null){
return;
}
queue.offer(root);
helper(root.left);
helper(root.right);
}
}
按照先序遍历,我们将每个节点依次入队,最后出队并设置右指针和左指针即可。详细请看代码,有疑问欢迎留言。