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

    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],
    ]
    

     解题思路:

    充分利用数据结构。

    /**
     * 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> > levelOrderBottom(TreeNode *root) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            vector<vector<int>> ans;
            if(root == NULL) return ans;
            vector<TreeNode*> cur;
            vector<int> curVal;
            cur.push_back(root);
            curVal.push_back(root -> val);
            while(!cur.empty())
            {
                vector<vector<int>>::iterator it = ans.begin();
                ans.insert(it, curVal);
                vector<TreeNode*> tmp;
                vector<int> tmpVal;
                for(int i = 0;i < cur.size();i++)
                {
                    if(cur[i] -> left != NULL) 
                    {
                        tmp.push_back(cur[i] -> left);
                        tmpVal.push_back(cur[i] -> left -> val);
                    }
                    if(cur[i] -> right != NULL) 
                    {
                        tmp.push_back(cur[i] -> right);
                        tmpVal.push_back(cur[i] -> right -> val);
                    }
                }
                cur = tmp;
                curVal = tmpVal;
            }
            return ans;
        }
    };
  • 相关阅读:
    realsense d435i qt 测试
    realsense d435i 数据 测试
    realsense d435i测试
    ubuntu torch GPU yolov5
    IfcLayeredItem
    ubuntu大服务器 pytorch环境配置
    condarc内容
    realsense point cloud
    yolov5 环境配置
    pip error
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3417456.html
Copyright © 2011-2022 走看看