您的位置:首页 > 其它

[LeetCode] Flatten Binary Tree to Linked List

2014-04-22 17:41 351 查看
Total Accepted: 10982Total Submissions:40794My
Submissions

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;

flatten(root.left);
flatten(root.right);

TreeNode node = root.left;

if (root.left != null) {
// get last node in left tree
while (node.right != null) node = node.right;
node.right = root.right;
root.right = root.left;
root.left = null;
}
}
}


 

public class Solution {
// store current last node
private TreeNode last;
public void flatten(TreeNode root) {
if (root == null) return;

TreeNode tmp = root.right;

if (last == null) last = root;
else {
last.right = root;
last = root;
}

flatten(root.left);
flatten(tmp);

root.left = null;
}
}


// without recursion
public class Solution {
// store current last node
public void flatten(TreeNode root) {

while (root != null) {
if (root.left != null) {
// get bigest element in left tree
TreeNode p = root.left;
while (p.right != null) p = p.right;
p.right = root.right;
root.right = root.left;
root.left = null;
}

root = root.right;
}
}
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode Binary Tree