标签:des style blog class code c
本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
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.
题意:从底往上按层遍历二叉树
思路:
思路和Binary Tree Level Order Traveral 一样,
即从上往下按层遍历二叉树,将每一层的节点存放到该层对应的数组中
最后将得到的数组倒转一下就可以了
按层遍历二叉树可用bfs,也可用dfs,但都要记录节点所在的层
复杂度:时间O(n), 空间O(n)
相关题目:
Binary Tree Level Order Traversal
Binary Tree Zigzag Level Order Traversal
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void levelOrderBottom(TreeNode *root, int level, vector<vector<int> >&result) { if(!root) return ; if(level >= result.size()) { vector<int> temp; temp.push_back(root->val); result.push_back(temp); } else result[level].push_back(root->val); levelOrderBottom(root->left, level + 1, result); levelOrderBottom(root->right, level + 1, result); } vector<vector<int> > levelOrderBottom(TreeNode *root){ vector<vector<int> >result; levelOrderBottom(root, 0, result); reverse(result.begin(), result.end()); return result; } };
Leetcode 树 Binary Tree Level Order Traversal II,布布扣,bubuko.com
Leetcode 树 Binary Tree Level Order Traversal II
标签:des style blog class code c
原文地址:http://blog.csdn.net/zhengsenlie/article/details/25729377