樹(shù)的遍歷

1、利用遞歸的方式獲取樹(shù)的前序遍歷結(jié)果

 //獲取樹(shù)的前序遍歷
public static String preTraver(TreeNode root){
    if (root!=null) {
        re += root.val;
        if (root.left != null)
            preTraver(root.left);
        if (root.right != null)
            preTraver(root.right);
    }
    return re;
}

2、 利用遞歸的方式獲取樹(shù)的中序遍歷結(jié)果

    //獲取樹(shù)的中序遍歷
public static String medTraver(TreeNode root){
    if (root!=null) {
        if (root.left != null)
            medTraver(root.left);
        re += root.val;
        if (root.right != null)
            medTraver(root.right);
    }
    return re;
}

3、利用遞歸的方式獲取樹(shù)的后序遍歷結(jié)果

//獲取樹(shù)的后序遍歷
public static String aftTraver(TreeNode root){
    if (root!=null) {
        if (root.left != null)
            preTraver(root.left);
        if (root.right != null)
            preTraver(root.right);
        re += root.val;
    }
    return re;
}

4、利用隊(duì)列實(shí)現(xiàn)層次遍歷

//獲取樹(shù)的層次遍歷
public static String levelTraver(TreeNode root){
    Queue<TreeNode> queue = new ArrayDeque<TreeNode>();
    TreeNode node;
 if (root!=null)
     queue.offer(root);
 while (!queue.isEmpty()){
     node=queue.poll();
     re+=node.val;
     if (node.left!=null)
         queue.offer(node.left);
     if (node.right!=null)
         queue.offer(node.right);
 }
    return re;
}

0 ??? 1 ???2 ??? 3 ???4 ??? 5 ???6 ??? 7 ???8 ??? 9 ???10 ??? 11 ???12 ??? 13 ???14 ??? 15 ???16 ??? 17 ???
18 ??? 19 ???20 ??? 21 ???22 ??? 23 ???24 ??? 25 ???26 ??? 27 ???28 ??? 29 ???30 ??? 31 ???32 ??? 33 ???34 ??? 35 ???
36 ??? 37 ???38 ??? 39 ???40 ??? 41 ???42 ??? 43 ???44 ??? 45 ???

<center>Coding Blog ??? Github Blog </center>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容