102. Binary Tree Level Order Traversal

来源:互联网 发布:网络上刘皇叔是什么梗 编辑:程序博客网 时间:2024/04/30 03:19

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,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
bfs思路

/** * 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:    vector<vector<int>> levelOrder(TreeNode* root) {        vector<TreeNode*> father, son;        father.push_back(root);        vector<vector<int>> ans;        if(root == NULL) return ans;        else ans.push_back({root->val});        vector<int> tmp;        int cnt = 0;        while(1){            if(root->left != NULL){                son.push_back(root->left);                tmp.push_back(root->left->val);            }            if(root->right != NULL){                son.push_back(root->right);                tmp.push_back(root->right->val);            }            ++cnt;            if(cnt == father.size()){                father = son;                cnt = 0;                if(father.empty())                    break;                ans.push_back(tmp);                son.clear();                tmp.clear();            }            root = father[cnt];        }        return ans;    }};
0 0
原创粉丝点击