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

    class Solution {
    private:
        vector<vector<int> > nodes;
    public:
        vector<vector<int> > levelOrderBottom(TreeNode *root) {
            nodes.clear();
            dfs(root, 0);
            reverse(nodes.begin(), nodes.end());
            return nodes;
        }
        void dfs(TreeNode* root, int level) {
            if (root == NULL) return;
            if (level >= nodes.size()) {
                nodes.push_back(vector<int>());
            }
            nodes[level].push_back(root->val);
            dfs(root->left, level + 1);
            dfs(root->right, level + 1);
        }
    };

    复杂度应该不会有不同, 应该有更好的方法,不用做reverse

    第二轮:

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

    几乎一样的代码,可以用链表避免做reverse


    第三轮:
    先求出树德最大高度就可以避免做reverse。
    /**
     * 7:13
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    private:
        vector<vector<int> > res;
    public:
        vector<vector<int>> levelOrderBottom(TreeNode* root) {
            int h = height(root);
            res = vector<vector<int> >(h);
            if (h == 0) {
                return res;
            }
            dfs(root, h - 1);
            return res;
        }
        
        int height(TreeNode* root) {
            if (root == NULL) {
                return 0;
            }
            int dl = height(root->left);
            int dr = height(root->right);
            
            return 1 + max(dl, dr);
        }
        
        void dfs(TreeNode* root, int idx) {
            if (root == NULL) {
                return; 
            }
            
            dfs(root->left, idx - 1);
            dfs(root->right, idx - 1);
            
            res[idx].push_back(root->val);
        }
    };


  • 相关阅读:
    glog入门demo
    gflag的简单入门demo
    caffe库源码剖析——net层
    排序算法的c++实现——计数排序
    docker的/var/lib/docker目录迁移
    SpringCloud Ribbon 负载均衡 通过服务器名无法连接的神坑一个
    Spring Boot Cache使用与整合
    Navicat Keygen
    Windows / Office
    docker swarm 搭建与服务更新
  • 原文地址:https://www.cnblogs.com/lailailai/p/3688725.html
Copyright © 2011-2022 走看看