首页 > 代码库 > Leetcode#107 Binary Tree Level Order Traversal II

Leetcode#107 Binary Tree Level Order Traversal II

原题地址

 

二叉树层次遍历,最后把遍历结果翻转一下即可

 

代码:

 1 vector<vector<int> > levelOrderBottom(TreeNode *root) { 2         vector<vector<int> > res; 3         queue<TreeNode *> layer; 4          5         layer.push(root); 6         while (!layer.empty()) { 7             queue<TreeNode *> nextLayer; 8             vector<int> path; 9             10             while (!layer.empty()) {11                 TreeNode *front = layer.front();12                 layer.pop();13                 if (!front)14                     continue;15                 path.push_back(front->val);16                 nextLayer.push(front->left);17                 nextLayer.push(front->right);18             }19             if (path.size() > 0)20                 res.push_back(path);21             layer = nextLayer;22         }23         24         vector<vector<int> > tra;25         for (int i = res.size() - 1; i >= 0; i--)26             tra.push_back(res[i]);27             28         return tra;29 }

 

Leetcode#107 Binary Tree Level Order Traversal II