首页 > 代码库 > Leetcode 树 Binary Tree Level Order Traversal II
Leetcode 树 Binary Tree Level Order Traversal II
本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
Binary Tree Level Order Traversal II
Total Accepted: 10080 Total Submissions: 32610Given 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; } };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。