[LeetCode]102. Binary Tree Level Order Traversal

前端之家收集整理的这篇文章主要介绍了[LeetCode]102. Binary Tree Level Order Traversal前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Problem:

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

For example:
Given binary tree {3,9,20,#,15,7},

     3
    / \
   9  20
     /  \
    15   7

return its level order traversal as:
[
[3],
[9,20],
[15,7]
]

Answer:

使用递归,并维护一个深度

> res;
    void dfs(TreeNode* t,int d){
        if(t==NULL) return;
        if(res.size()<=d) res.push_back(vector());
        res[d].push_back(t->val);
        if(t->left) dfs(t->left,d+1);
        if(t->right) dfs(t->right,d+1);
        return;
    }
    vector> levelOrder(TreeNode* root) {
        if(root==NULL) return res;
        dfs(root,0);
        return res;
    }
};
原文链接:https://www.f2er.com/note/422440.html

猜你在找的程序笔记相关文章