Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). For example:Given binary tree [3,9,20,null,null,15,7] / \ / \ return its level order traversal as: [ [], [,], [,] ] 二叉树的层次遍历使用队列来实现,…
本题也属于层次遍历的变形,不同之处在于其遍历的方法是交替进行的,形成一个ZigZag的曲线形式,如下: 代码如下: struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x): val(x), left(NULL),right(NULL) {} }; void Swap(vector<int> &ivec) { ; int len = ivec.size(); ; i < len/; i…
题目 给定一个二叉树,返回其节点值的锯齿形层次遍历.(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行). 例如: 给定二叉树 [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 返回锯齿形层次遍历如下: [ [3], [20,9], [15,7] ] 考点 1.stack 双栈 2.tree 3.vector 思路 设置两个栈 , 分别用于存储不同层的子节点,存储的顺序和打印的顺序相反,所以用栈实现. 为什么用两个栈,不用一个栈,通过上…
这道题是LeetCode里的第102道题. 题目要求: 给定一个二叉树,返回其按层次遍历的节点值. (即逐层地,从左到右访问所有节点). 例如: 给定二叉树: [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 返回其层次遍历结果: [ [3], [9,20], [15,7] ] 解题代码: /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *…
基础为用队列实现二叉树的层序遍历,本题变体是分别存储某一层的元素,那么只要知道,每一层的元素都是上一层的子元素,那么只要在while循环里面加个for循环,将当前队列的值(即本层元素)全部访问后再执行下一个循环就可以了. C++代码: /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val…
给定一个二叉树,返回其按层次遍历的节点值. (即zhu'ceng'de,从左到右访问).例如:给定二叉树: [3,9,20,null,null,15,7],    3   / \  9  20    /  \   15   7返回其层次遍历结果为:[  [3],  [9,20],  [15,7]]详见:https://leetcode.com/problems/binary-tree-level-order-traversal/description/ Java实现: /** * Definit…
给定一个二叉树,返回其按层次遍历的节点值. (即逐层地,从左到右访问所有节点). 例如: 给定二叉树: [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 返回其层次遍历结果: [ [3], [9,20], [15,7] ] class Solution { public: vector<vector<int> > levelOrder(TreeNode* root) { vector<vector<int> > res…
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). For example:Given binary tree {3,9,20,#,#,15,7}, 3 / \ 9 20 / \ 15 7 return its…
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). For example:Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 retur…
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). For example:Given binary tree{3,9,20,#,#,15,7}, 3 / \ 9 20 / \ 15 7 return its z…