107. 二叉樹(shù)的層序遍歷 II (力扣)

題目:給定一個(gè)二叉樹(shù),返回其節(jié)點(diǎn)值自底向上的層序遍歷。 (即按從葉子節(jié)點(diǎn)所在層到根節(jié)點(diǎn)所在的層,逐層從左向右遍歷)
例如:
給定二叉樹(shù) [3,9,20,null,null,15,7],

3
/ \
9 2
?/ \
?15 7
返回其自底向上的層序遍歷為:

[
[15,7],
[9,20],
[3]
]

思路講解: Arraylist 實(shí)現(xiàn) 的List 接口,存放類型是 一個(gè) List集合, 利用 dfs 進(jìn)行層次遍歷, 最后的結(jié)果需要借助 Collections 類 的 reverse 方法,實(shí)現(xiàn)自 底向上的展示。
實(shí)際還是二叉樹(shù)的層次遍歷。

void reverse(List list):對(duì)指定 List 集合元素進(jìn)行逆向排序。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
 import java.util.Collections;

class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if(root == null){
            return result;
        }
        DFS(root,result,0);
        Collections.reverse(result);
        return result;
    }

    void  DFS(TreeNode root,List<List<Integer>> result,int height){
        if(root == null){
            return;
        }

        if(height >= result.size()){
            result.add(new ArrayList<>());
        }
      
        result.get(height).add(root.val);
        
        DFS(root.left, result,height + 1);
        DFS(root.right,result,height + 1);
    }

}

鏈接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/solution/san-chong-shi-xian-tu-jie-107er-cha-shu-de-ceng-ci/

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容