给定一个二叉树,原地将它展开为链表。
例如,给定二叉树
1 / 2 5 / 3 4 6
将其展开为:
1 2 3 4 5 6
解法
解法一:
1.对树进行先序遍历,把每遍历一个节点就将该节点入队
2.遍历完之后,对队列进行出队操作
3.每出一个节点,就将该节点的left指针置为null,右指针指向下一个出队的节点
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { Queue<TreeNode> queue; public void flatten(TreeNode root) { //1,2,3,4,5,6 先序 //先序遍历二叉树,把每个节点入队 //把先序遍历后的队列出队:left =null,right=下一个节点 if(root!=null){ queue = new LinkedList<TreeNode>(); pre(root); TreeNode head = new TreeNode(0); TreeNode p = head; for(TreeNode q : queue){ q.left=null; p.right = q; p = p.right; } } } public void pre(TreeNode root) { this.queue.offer(root); if(root.left!=null) pre(root.left); if(root.right!=null) pre(root.right); } }
解法二:
/** * 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) { if (root == null) return; Stack<TreeNode> stk = new Stack<TreeNode>(); stk.push(root); while (!stk.isEmpty()){ TreeNode curr = stk.pop(); if (curr.right!=null) stk.push(curr.right); if (curr.left!=null) stk.push(curr.left); if (!stk.isEmpty()) curr.right = stk.peek(); curr.left = null; // dont forget this!! } } }