本文共 1070 字,大约阅读时间需要 3 分钟。
1.问题描述:
给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)。
2.样例:
给一棵二叉树 {3,9,20,#,#,15,7}
:
3 / \9 20 / \ 15 7
返回他的分层遍历结果:
[ [3], [9,20], [15,7]]
3.代码: /** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */class Solution {public: /* * @param root: A Tree * @return: Level order a list of lists of integer */ vector> levelOrder(TreeNode * root) { // write your code here vector > order; queue queue; int len; if(root == NULL) { return order; } queue.push(root); len = queue.size(); while(!queue.empty()) { vector base; len = queue.size(); while(len--) { TreeNode *tmp=queue.front(); base.push_back(tmp->val); queue.pop(); if(tmp->left) queue.push(tmp->left); if(tmp->right) queue.push(tmp->right); } order.push_back(base); } return order; }};
转载地址:http://fouii.baihongyu.com/