Leetcode-102 Binary Tree Level Order Traversal

Leetcode-102

Posted by frankie on February 18, 2020

分析

分析

BFS

BFS

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        if (!root) {
            return {};
        }
        vector<vector<int> > levels;
        queue<TreeNode*> todo;
        todo.push(root);
        while (!todo.empty()) {
            levels.push_back({});
            for (int i = 0, n = todo.size(); i < n; i++) {
                TreeNode* node = todo.front();
                todo.pop();
                levels.back().push_back(node -> val);
                if (node -> left) {
                    todo.push(node -> left);
                }
                if (node -> right) {
                    todo.push(node -> right);
                }
            }
        }
        return levels;
    }
};

DFS

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:

    void dfs(TreeNode* root, int depth, vector<vector<int> >& ans) {

        if (!root)
            return;

        if (ans.size() <= depth){
            ans.push_back({});
        }

        ans[depth].push_back(root->val);

        dfs(root->left,  depth+1, ans);
        dfs(root->right, depth+1, ans);

    }

    vector<vector<int>> levelOrder(TreeNode* root) {

        if (!root)
            return {};

        vector<vector<int> > ans;

        dfs(root, 0, ans);

        return ans;
    }
};