# [LeetCode] 102. Hierarchical traversal of binary tree (C + +)

Title Description:

Given a binary tree, it returns the value of the nodes it traverses hierarchically. (that is, access all nodes layer by layer, from left to right).

For example:
Given a binary tree: [3,9,20,null,null,15,7],

```    3
/ \
9  20
/  \
15   7
```

Return its hierarchical traversal result:

```[
,
[9,20],
[15,7]
]```

Use queues for hierarchical traversal:

Because this problem does not only need to traverse hierarchically, and the final results need to be saved hierarchically (that is, each layer of nodes is saved in a vector), so it needs a depth record which is the current layer, a cout record that there are several nodes in this layer, and then use the queue first in first out to traverse all nodes one by one.

```/**
* 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) {
if(root==nullptr)return vector<vector<int>>{};
queue<TreeNode*> data;
vector<vector<int>> res;
data.push(root);
int depth=0;
while(!data.empty()){
res.push_back(vector<int> {});//What layer of storage space will be opened up
int cout = data.size();//What layer has cout nodes
while(cout--){//Traversal layer
res[depth].push_back(root->val);
if(root->left != nullptr)data.push(root->left);
if(root->right != nullptr)data.push(root->right);
data.pop();
if(!data.empty())root = data.front();
}
depth += 1;//Layer number plus 1
}
return res;
}
};```

Recursive preamble traversal: (refer to leetcode comments)

• Use the depth variable to record the current layer (starting from 0), and enter the lower layer when depth + 1;
• If depth > = vector. Size() indicates that this layer has not been used yet, this is the first time, so we need to expand the capacity;
• Because it's preorder traversal, middle left right. For each layer, the left one must be traversed before the right one. In fact, the order in the subsequent order is the same
```class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ans;
pre(root, 0, ans);
return ans;
}

void pre(TreeNode *root, int depth, vector<vector<int>> &ans) {
if (!root) return ;//void
if (depth >= ans.size())
ans.push_back(vector<int> {});
ans[depth].push_back(root->val);
pre(root->left, depth + 1, ans);
pre(root->right, depth + 1, ans);
}
};```

Posted by Sneo on Sun, 01 Dec 2019 19:28:47 -0800