用记事本做网站,推广网页模板,手机版网站原理,联通套餐先定义一个二叉树的结点 再创建二叉树#xff0c;这里就不写了#xff0c;之前的有创建二叉树的博客。
层序遍历
用到栈的思想#xff0c; 1 先让根 节点进队列#xff0c;2 然后读队顶元素#xff0c;3 让他出队列4 打印它的值5 让队顶元素的左右子树进栈#xff0…先定义一个二叉树的结点 再创建二叉树这里就不写了之前的有创建二叉树的博客。
层序遍历
用到栈的思想 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:vectorvectorint levelOrder(TreeNode* root) {vectorvectorintret;if(rootNULL){return ret;}queuelevelNode q;levelNode ln{0,root};q.push(ln);while(!q.empty()){levelNode front q.front();q.pop();if(ret.size() front.level){vectorintv;ret.push_back(v);}ret[front.level].push_back(front.root-val);if(front.root-left!NULL){levelNode lnc {front.level1,front.root-left};q.push(lnc);}if(front.root-right!NULL){levelNode lnc {front.level1,front.root-right};q.push(lnc);}}return ret;}
};