(LeetCode 面试经典 150 题) 103. 二叉树的锯齿形层序遍历(广度优先搜索bfs)
题目:103. 二叉树的锯齿形层序遍历
思路:广度优先搜索bfs,时间复杂度0(n)。
C++版本:
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode() : val(0), left(nullptr), right(nullptr) {}* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}* };*/
class Solution {
public:vector<vector<int>> zigzagLevelOrder(TreeNode* root) {vector<vector<int>> ans;if(root==nullptr) return ans;queue<TreeNode *> qu;qu.push(root);// 当前层节点数不为0while(qu.size()>0){// 当前层节点数int n=qu.size();vector<int> v;for(int i=0;i<n;i++){TreeNode * tmp=qu.front();qu.pop();v.push_back(tmp->val);if(tmp->left!=nullptr) qu.push(tmp->left);if(tmp->right!=nullptr) qu.push(tmp->right);}if(ans.size()%2==1) reverse(v.begin(),v.end());ans.push_back(v);}return ans;}
};
JAVA版本:
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {public List<List<Integer>> zigzagLevelOrder(TreeNode root) {List<List<Integer>> ans=new ArrayList<>();if(root==null) return ans;Queue<TreeNode> qu=new LinkedList<>();qu.add(root);while(qu.size()>0){int n=qu.size();List<Integer> v=new ArrayList<>();for(int i=0;i<n;i++){TreeNode tmp=qu.poll();v.add(tmp.val);if(tmp.left!=null) qu.add(tmp.left);if(tmp.right!=null) qu.add(tmp.right);}if(ans.size()%2==1) Collections.reverse(v);ans.add(v);}return ans;}
}
GO版本:
/*** Definition for a binary tree node.* type TreeNode struct {* Val int* Left *TreeNode* Right *TreeNode* }*/
func zigzagLevelOrder(root *TreeNode) [][]int {ans:=[][]int{}if root==nil {return ans}qu:=[]*TreeNode{root}for len(qu)>0 {n:=len(qu)v:=make([]int,n)for i:=0;i<n;i++ {tmp:=qu[0]qu=qu[1:]if len(ans)%2==0 {v[i]=tmp.Val}else{v[n-i-1]=tmp.Val}if tmp.Left!=nil {qu=append(qu,tmp.Left)}if tmp.Right!=nil {qu=append(qu,tmp.Right)}}ans=append(ans,v)}return ans}