• Binary Tree Level Order Traversal II [LeetCode]


    Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

    For example:
    Given binary tree {3,9,20,#,#,15,7},

        3
       / 
      9  20
        /  
       15   7
    

    return its bottom-up level order traversal as:

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

    BFS solution:

     1     vector<vector<int> > levelOrderBottom(TreeNode *root) {
     2         vector<vector<int> > ret;
     3         if(root == NULL)
     4             return ret;
     5         vector<TreeNode *> level;
     6         level.push_back(root);
     7         while(true) {
     8             if(level.size() == 0)
     9                 break;
    10             vector<int> nums;
    11             vector<TreeNode *> tmp;  
    12             for(auto item : level) {
    13                 nums.push_back(item->val);
    14                 if(item->left != NULL)
    15                     tmp.push_back(item->left);
    16                 if(item->right != NULL)
    17                     tmp.push_back(item->right);
    18             }
    19             ret.insert(ret.begin(), nums);
    20             level = tmp;
    21         }
    22         return ret;
    23     }

    DFS solution:

     1     void getLevelNums(TreeNode *root, vector<vector<int> > &ret, int level) {
     2         if(ret.size() < level + 1){
     3             vector<int> nums; 
     4             nums.push_back(root->val);
     5             ret.insert(ret.begin(), nums);
     6         }else if (ret.size() >= level + 1) {
     7             ret[ret.size() - level - 1].push_back(root->val);
     8         }
     9 
    10         if(root->left != NULL)
    11             getLevelNums(root->left, ret, level + 1);
    12 
    13         if(root->right != NULL)
    14             getLevelNums(root->right, ret, level + 1);
    15         
    16     }
    17     vector<vector<int> > levelOrderBottom(TreeNode *root) {
    18         vector<vector<int> > ret;
    19         if(root == NULL)
    20             return ret;
    21         getLevelNums(root, ret, 0);
    22         return ret;
    23     }
  • 相关阅读:
    辞职信(转贴)
    去掉控件上显示聚焦框
    静态构造函数
    用Excel 公式求 金额的差额
    2020/2/6学习总结
    2020/2/3学习总结
    2020/2/7学习总结
    2020/1/31学习总结
    2020/2/5学习总结
    2020/2/4学习总结
  • 原文地址:https://www.cnblogs.com/guyufei/p/3419295.html
Copyright © 2020-2023  润新知