劍指offer 二叉樹轉爲雙向鏈表

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {
    private TreeNode head=null;
    private TreeNode tail=null;
    public TreeNode Convert(TreeNode pRootOfTree) {
        visit(pRootOfTree);
        return head;
    }
    public void visit(TreeNode root) {  
        if (root == null) {  
            return;  
        }  
        visit(root.left);  
        createList(root);  
        visit(root.right);  
    }  
    public void createList(TreeNode cur){  
        cur.left=tail;//把當前的節點接到鏈表的尾部   
        if(tail!=null){//雙向連接   
            tail.right=cur;   
        }else{   
            head=cur;   
        }   
        tail=cur;//更新尾結點爲當前結點,或者說:尾結點後移   
    }  
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章