Problem Description: Given a binary tree, flatten it to a linked list in-place.
Solution: 对二叉树进行前序遍历(pre-order).
1 public void flatten(TreeNode root) { 2 if (root == null) return; 3 List<TreeNode> queue = new ArrayList<TreeNode>(); 4 Stack<TreeNode> stack = new Stack<TreeNode>(); 5 stack.push(null); 6 TreeNode top =root; 7 while (top != null) { 8 queue.add(top); 9 if (top.right != null) stack.push(top.right); 10 if (top.left != null) stack.push(top.left); 11 top = stack.pop(); 12 } 13 14 for (int i = 0; i < queue.size(); i++) { 15 TreeNode node = queue.get(i); 16 node.left = null; 17 if (i < queue.size() - 1) 18 node.right = queue.get(i+1); 19 } 20 }
Problem Flatten Binary Tree
时间: 2024-11-08 02:27:41