【发布时间】:2015-11-04 02:58:14
【问题描述】:
这是问题。
给定一棵二叉树,我们需要从叶子节点中创建链表。限制是它应该使用 O(1) 额外空间来完成。我们也可以使用 node->right 指针来连接链表。
给定下面的树。
10
5 12
7 11 15
结果应该是:
10
5 12
L -> 7 -> 11 -> 15
注意L是一个新的Pointer,它引用叶子节点,每个叶子节点都有指向它们的正确指针。
这是我尝试过的:
public class TreeManipulationMethods {
private static IntTreeNode linkedlist=null;
private static IntTreeNode prev=null;
private static int preIndex=0;
private static Node headNode;
public static void main(String[] args){
IntTreeNode tree1=new IntTreeNode(10);
tree1.left=new IntTreeNode(5);
tree1.left.right=new IntTreeNode(7);
tree1.right=new IntTreeNode(12);
tree1.right.left=new IntTreeNode(11);
tree1.right.right=new IntTreeNode(15);
convertToLinkedListWithOnlyLeafNodes(tree1);
linkedlist.printRight();
}
public static void convertToLinkedListWithOnlyLeafNodes(IntTreeNode root){
if (root==null)
return;
convertToLinkedListWithOnlyLeafNodes(root.left);
if (isLeaf(root)){
if (linkedlist==null)
linkedlist=root;
else
prev.right=root;
prev=root;
}
convertToLinkedListWithOnlyLeafNodes(root.right);
}
private static boolean isLeaf(IntTreeNode root){
return root!=null || (root.left==null && root.right==null);
}
}
class IntTreeNode {
int val;
IntTreeNode right;
IntTreeNode left;
public IntTreeNode(int val){
this.val=val;
}
public void printRight(){
String toRet="[ ";
IntTreeNode current = this;
while(current!=null){
toRet+=current.val + " -> ";
current=current.right;
}
toRet+="NULL ]";
System.out.println(toRet);
}
}
输出是:
[ 5 -> 7 -> 10 -> 11 -> 12 -> 15 -> NULL ]
这显然是不正确的。
预期的输出将是
[7->11->15]
【问题讨论】:
标签: java algorithm linked-list binary-tree