LeetCode OJ:Binary Tree Level Order Traversal II

来源:互联网 发布:怎样联系淘宝小二 编辑:程序博客网 时间:2024/06/02 01:41

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

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


算法思想:

从前往后,从右向左处理完,然后逆序输出

/** * 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){vector<vector<int>> result;if(!root)return result;list<list<int>> r;list<int> t;int curLev=1;int nextLev=0;queue<TreeNode *> que;que.push(root);while(!que.empty()){TreeNode *cur=que.front();que.pop();t.push_front(cur->val);if(cur->right){nextLev++;que.push(cur->right);}if(cur->left){nextLev++;que.push(cur->left);}if(--curLev==0){r.push_front(t);t.clear();curLev=nextLev;nextLev=0;}}for(auto &v:r){vector<int> k;for(int i:v){k.push_back(i);}result.push_back(k);}return result;}};

递归版

/** * 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) {        vector<vector<int>> result;        traverse(root,1,result);        reverse(result.begin(),result.end());        return result;    }    void traverse(TreeNode *root,size_t level,vector<vector<int>> &result){        if(!root)return;        if(level>result.size())            result.push_back(vector<int>());        result[level-1].push_back(root->val);        traverse(root->left,level+1,result);        traverse(root->right,level+1,result);    }};


0 0
原创粉丝点击