问题:从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。剑指 Offer 32 - I. 从上到下打印二叉树 - 力扣(LeetCode)
思路:利用队列先入先出的性质,可以依次打印出每层的节点,即遍历完一个 front() 节点就 pop() ;
时间复杂度:O(N ); 空间复杂度:O(N )
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> levelOrder(TreeNode* root) { vector<int>v; if(root == nullptr) return v; queue<TreeNode*>q; q.push(root); while(q.size()){ TreeNode* node = q.front(); q.pop(); v.push_back(node->val); if(node->left) q.push(node->left); if(node->right) q.push(node->right); } return v; } };
加要求1:每层的节点对应一行,按行打印出节点
思路:嵌套一层循环,该循环次数是 外层循环int L = queue.size() 的大小,也即当前层的节点数,访问一个节点就pop() ;并且 L- - ;
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>>res; if(root == nullptr ) return res; queue<TreeNode*>q; q.push(root); while(q.size()){ vector<int>tmp; int L = q.size(); while(L--){ TreeNode* node = q.front(); q.pop(); tmp.push_back(node->val); if(node->left) q.push(node->left); if(node->right) q.push(node->right); } res.push_back(tmp); } return res; } };
加要求2:“之” 字形遍历遍历,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,
标签:node,遍历,TreeNode,---,right,二叉树,push,节点,left From: https://www.cnblogs.com/xuan01/p/17122416.html