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
method 1 recursive method:
public class Solution {
public void flatten(TreeNode root) {
if(root != null){
TreeNode aNode = root.left;
if(aNode != null){
while(aNode.right != null)
aNode = aNode.right;
aNode.right = root.right;
root.right = root.left;
root.left = null;
}
root = root.right;
flatten(root);
}
}
}
method2: preorder tree traversal method
public class Solution {
public void flatten(TreeNode root) {
Stack<TreeNode> nodes = new Stack<TreeNode>();
if(root != null){
TreeNode currentNode = root;
if(root.right != null)
nodes.push(root.right);
if(root.left != null){
nodes.push(root.left);
root.left = null;
}
while(!nodes.isEmpty()){
TreeNode aNode = nodes.pop();
currentNode.right = aNode;
//currentNode.left = null;
currentNode = currentNode.right;
if(aNode.right != null)
nodes.push(aNode.right);
if(aNode.left != null){
nodes.push(aNode.left);
aNode.left = null;
}
}
}
}
}
本文介绍了一种将二叉树结构转换为链表的方法,提供了两种不同的实现方式:递归方法和前序遍历方法。递归方法通过调整左右子节点连接,将左子树作为右子树进行展平;前序遍历方法则使用栈结构,迭代地展平二叉树。
121

被折叠的 条评论
为什么被折叠?



