二叉树的层序遍历,蛇形打印二叉树
class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>> res; //注意判断根为空的情况 if (root == NULL) return res; queue<TreeNode*> Q; Q.push(root); while (!Q.empty()) { //保存每一层的结点 vector<int> ans; //对队列中的同一层结点进行处理 int width = Q.size(); for (int i = 0; i < width; i++) { TreeNode* p = Q.front(); ans.push_back(p->val); Q.pop(); if (p->left) Q.push(p->left); if (p->right) Q.push(p->right); } res.push_back(ans); } return res; } };
#include<iostream> #include<queue> #include<math.h> #include<algorithm> using namespace std; int a[100005]; struct node { int val; node* left; node* right; }Treenode[1000]; node* creat(int n) { //初始化数组 for (int i = 1; i <= n; i++) { Treenode[i].left = nullptr; Treenode[i].right = nullptr; Treenode[i].val = i; } for (int i = 1; i <= n / 2; i++) { if(i*2<=n) Treenode[i].left = &Treenode[i * 2]; if(i*2+1<=n) Treenode[i].right =&Treenode[i * 2 + 1]; } return &Treenode[1]; } void Print(node* root) { queue<node*>p; p.push(root); while (!p.empty()) { node* temp = p.front(); p.pop(); if (temp != nullptr) { cout << temp->val << endl; if(temp->left!=nullptr) p.push(temp->left); if(temp->right!=nullptr) p.push(temp->right); } } } int main() { node* root = creat(100); Print(root); return 0; }
go版本
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func levelOrder(root *TreeNode) [][]int { que:=make([]*TreeNode,0) que=append(que,root) ans:=make([][]int,0) if root==nil{ return ans } for len(que)!=0{ size:=len(que) ans2:=make([]int,0) for i:=0;i<size;i++{ front:=que[0] ans2=append(ans2,front.Val) que=que[1:] if front.Left!=nil{ que=append(que,front.Left) } if front.Right!=nil{ que=append(que,front.Right) } } ans=append(ans,ans2) } return ans }
蛇形打印二叉树
https://leetcode.cn/problems/binary-tree-zigzag-level-order-traversal/
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func zigzagLevelOrder(root *TreeNode) [][]int { que:=make([]*TreeNode,0) que=append(que,root) ans:=make([][]int,0) if root==nil{ return ans } depth:=0 //标记层数,奇数层需要翻转 for len(que)!=0{ size:=len(que) ans2:=make([]int,0) for i:=0;i<size;i++{ front:=que[0] ans2=append(ans2,front.Val) que=que[1:] if front.Left!=nil{ que=append(que,front.Left) } if front.Right!=nil{ que=append(que,front.Right) } } if depth%2==1{ ans=append(ans,reveser(ans2)) }else{ ans=append(ans,ans2) } depth++ } return ans } func reveser(ans []int) []int{ tmp:=make([]int,0) for i:=len(ans)-1;i>=0;i--{ tmp=append(tmp,ans[i]) } return tmp }
等风起的那一天,我已准备好一切