先定義一個二叉樹的結點
再創建二叉樹,這里就不寫了,之前的有創建二叉樹的博客。
層序遍歷
用到棧的思想,
1 先讓根 節點進隊列,2 然后讀隊頂元素,3 讓他出隊列4 打印它的值5 讓隊頂元素的左右子樹進棧,當它的左右子樹都不為空時執行6 并一直執行此操作,直到遍歷完
當隊列中無元素時,便把整個樹遍歷完了。
c++版本
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*///用來表示隊列中存放的數據類型struct levelNode{int level;TreeNode *root;};
class Solution {
public:vector<vector<int>> levelOrder(TreeNode* root) {vector<vector<int>>ret;if(root==NULL){return ret;}queue<levelNode> q;levelNode ln={0,root};q.push(ln);while(!q.empty()){levelNode front =q.front();q.pop();if(ret.size() <= front.level){vector<int>v;ret.push_back(v);}ret[front.level].push_back(front.root->val);if(front.root->left!=NULL){levelNode lnc = {front.level+1,front.root->left};q.push(lnc);}if(front.root->right!=NULL){levelNode lnc = {front.level+1,front.root->right};q.push(lnc);}}return ret;}
};