Binary Tree Level Order Traversal

来源:互联网 发布:结构优化是什么意思 编辑:程序博客网 时间:2024/05/29 21:18

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,#,#,15,7},

    3   / \  9  20    /  \   15   7

return its level order traversal as:

[  [3],  [9,20],  [15,7]]

二叉树的层次遍历,利用两个队列,从根节点开始,放到第一个队列中,下一层次的节点放到另一个队列中,以此类推!(注意对空树的处理)

/** * Definition for binary tree * 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) {queue<TreeNode*>q1;vector<vector<int>>ovec;vector<int>ivec;TreeNode *temp = root;if(!temp)    return ovec;q1.push(temp);do{queue<TreeNode*>q2;;while (!q1.empty()){temp = q1.front();ivec.push_back(temp->val);q1.pop();if (temp->left)q2.push(temp->left);if (temp->right)q2.push(temp->right);}ovec.push_back(ivec);ivec.clear();q1 = q2;} while (!q1.empty());return ovec;}};



0 0
原创粉丝点击