For example,
Given
1 / \ 2 5 / \ \ 3 4 6The 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 { private Queue<TreeNode> queue; public void flatten(TreeNode root) { queue = new LinkedList<>(); preorder(root); TreeNode node = null; while (!queue.isEmpty()) { if (node == null) { node = queue.poll(); node.left = null; } else { node.right = queue.poll(); node.left = null; node = node.right; } } } private void preorder(TreeNode root) { if (root == null) return; queue.offer(root); preorder(root.left); preorder(root.right); } }
No comments:
Post a Comment