102. Binary Tree Level Order Traversal

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

07/04/2017更新

前天周三,覃超說這題可以用DFS做。就做了一下。
精巧的地方在于res.get(level).add(node.val);這一句。按照DFS的思想考慮的話,它會把樹的每層最左邊節(jié)點存成一個cell list放到res里去,然后再backtracking回來,拿到那一level的節(jié)點繼續(xù)往響應(yīng)的leve 所在的cell list里面加。

如下:


    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) return res;
        dfs(res, root, 0);
        return res;
    }

    private void dfs(List<List<Integer>> res, TreeNode node, int level) {
        if (node == null) return;
        if (level >= res.size()) {
            res.add(new ArrayList<Integer>());
        }
        res.get(level).add(node.val);
        dfs(res, node.left, level + 1);
        dfs(res, node.right, level + 1);
    }

初版

這題跟求Maximum depth of a binary的非遞歸方法非常像,用一個queue保存結(jié)點。

Code Ganker的講解太好了:
這道題要求實現(xiàn)樹的層序遍歷,其實本質(zhì)就是把樹看成一個有向圖,然后進(jìn)行一次廣度優(yōu)先搜索,這個圖遍歷算法是非常常見的,這里同樣是維護(hù)一個隊列,只是對于每個結(jié)點我們知道它的鄰接點只有可能是左孩子和右孩子,具體就不仔細(xì)介紹了。算法的復(fù)雜度是就結(jié)點的數(shù)量,O(n),空間復(fù)雜度是一層的結(jié)點數(shù),也是O(n)。

public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) return res;
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        //本層結(jié)點數(shù)
        int curNum = 1;
        //下一層結(jié)點數(shù)
        int nextNum = 0;
        List<Integer> cell = new ArrayList<>();
        while (!queue.isEmpty()) {
            TreeNode temp = queue.poll();
            curNum--;
            cell.add(temp.val);

            if (temp.left != null) {
                queue.add(temp.left);
                nextNum++;
            }
            if (temp.right != null) {
                queue.add(temp.right);
                nextNum++;
            }
            if (curNum == 0) {
                res.add(cell);
                curNum = nextNum;
                nextNum = 0;
                
                cell = new ArrayList<>();
            }
        }
        return res;
    }

注意不要把
List<Integer> cell = new ArrayList<>();寫到while循環(huán)里,否則會出現(xiàn)下面的錯誤。

Input:

[3,9,20,null,null,15,7]
Output:
[[3],[20],[7]]
Expected:
[[3],[9,20],[15,7]]

另外注意,queue要用poll方法取數(shù)而不是pop。

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

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

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