Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1 / \ 2 5 / \ \ 3 4 6
The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
递归:
/**
* 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;
flatten(root.left);
flatten(root.right);
if (root.left == null)
return;
TreeNode node = root.left;
while (node.right != null) {
node = node.right;
}
node.right = root.right;
root.right = root.left;
root.left = null;
}
}
迭代:
/**
* 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> s= new Stack<>();
s.push(root);
while (!s.isEmpty()) {
TreeNode node = s.pop();
if (node.right != null) {
s.push(node.right);
}
if (node.left != null) {
s.push(node.left);
}
if (!s.isEmpty()) {
node.right = s.peek();
}
node.left = null;
}
}
}