zoukankan      html  css  js  c++  java
  • LeetCode --Binary Tree Level Order Traversal II

    题目链接

    在这题各种RE和WA。 方法上就是BFS, 还是基础不扎实的原因,很明显的一点就是这里使用二维vector, 开始的时候我竟然没有给ans分配空间,然后直接push_back, 导致RE到死。这点是必须引起注意的!

    附上代码:

     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     vector<vector<int> > levelOrderBottom(TreeNode *root) {
    13         vector<vector<int> > ans;
    14         typedef pair<TreeNode*, int> pii;        
    15         #define X first
    16         #define Y second
    17         if (root != NULL) {
    18             ans.resize(1);
    19             queue<pii> Q;
    20             //int level = 0, pre = -1;
    21             Q.push(pii(root, 0));
    22             while (!Q.empty()) {
    23                 
    24                 pii cur = Q.front(); Q.pop();
    25                 TreeNode *tmp = cur.X;
    26                 ans.resize(cur.Y+1);
    27                 ans[cur.Y].push_back(tmp->val);
    28                 
    29                 if (tmp->left != NULL) {
    30                     Q.push(pii(tmp->left, cur.Y+1));
    31                 }
    32                 if (tmp->right != NULL) {
    33                     Q.push(pii(tmp->right, cur.Y+1));
    34                 }
    35             }
    36             int len = ans.size();
    37             for (int i = 0; i < len/2; i++) {
    38                 swap(ans[i], ans[len-i-1]);
    39             }
    40         }
    41         return ans;
    42     }
    43 };
  • 相关阅读:
    摩根斯坦利面试
    Interview Preparation IV
    Interview Preparation III
    Interview Preparation II
    Interview Preparation I
    ASCII Characters
    Java Serialization
    贝莱德伦敦分部面试
    SVG基本知识
    前端知识整理(四)【HTTP相关】
  • 原文地址:https://www.cnblogs.com/Stomach-ache/p/3715595.html
Copyright © 2011-2022 走看看