【题目】
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1 / 2 5 / \ 3 4 6
The flattened tree should look like:
1 2 3 4 5 6
【解析】
题意是把一棵二叉树按照先序遍历的方式放到一棵只有右支树的二叉树中。
最开始想的思路是递归发,后来发现这样会溢出。
然后就用一个栈和一个队列来实现,队列用来存储先序遍历的结果,栈用于先序遍历。
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public void flatten(TreeNode root) { if (root == null) return; Stack<TreeNode> stack = new Stack<TreeNode>(); Queue<TreeNode> queue = new LinkedList<TreeNode>(); stack.push(root); queue.add(root); while (!stack.isEmpty()) { TreeNode top = stack.peek(); if (top.left != null) { queue.add(top.left); stack.push(top.left); top.left = null; } else if (top.right != null) { queue.add(top.right); stack.push(top.right); top.right = null; } else { //top.left == null && top.right == null stack.pop(); } } TreeNode node = queue.poll(); while (!queue.isEmpty()) { node.right = queue.poll(); node = node.right; } } }
时间: 2024-10-11 11:16:55