仅使用叶节点将binaryTree转换为LinkedList

时间:2015-08-11 18:26:30

标签: java algorithm linked-list binary-tree

这就是问题。

给定二叉树,我们需要从叶节点中创建链表。限制是它应该使用O(1)额外空间来完成。我们也可以使用node->右指针来连接链表。

鉴于下面的树。

      10

 5           12
     7   11      15

结果应为:

           10

     5           12
 L ->   7 -> 11  ->   15

注意L是一个新的指针,它引用了leafNodes,每个leafNodes都有正确的指针。

以下是我的尝试:

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]

1 个答案:

答案 0 :(得分:3)

由于您只需要添加叶节点,因此下面是条件  要成为叶子节点 - 它不应该离开&正确的节点,即root.left& root.right应为null

我想你需要做一个&&条件,如下所示

 root!=null && (root.left==null && root.right==null)

注意:这未经过测试。

相关问题