LeetCode OJ: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] ]
依旧是层序遍历而已,更另一篇博客一样,bfs或者dfs之后reverse一下就可以了,这里给出bfs版本,dfs见另一篇博文:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 private: 12 struct Node{ 13 TreeNode * treeNode; 14 int level; 15 Node(){} 16 Node(TreeNode * nd, int lv) 17 :treeNode(nd), level(lv){} 18 }; 19 public: 20 vector<vector<int>> levelOrderBottom(TreeNode* root) { 21 vector<vector<int>> ret; 22 if(!root) 23 return ret; 24 queue<Node> nodeQueue; 25 nodeQueue.push(Node(root, 0)); 26 int dep = -1; 27 while(!nodeQueue.empty()){ 28 Node node = nodeQueue.front(); 29 if(node.treeNode->left) 30 nodeQueue.push(Node(node.treeNode->left, node.level + 1)); 31 if(node.treeNode->right) 32 nodeQueue.push(Node(node.treeNode->right, node.level + 1)); 33 if(dep == node.level) 34 ret[dep].push_back(node.treeNode->val); 35 else{ 36 vector<int> tmp; 37 dep++; 38 ret.push_back(tmp); 39 ret[dep].push_back(node.treeNode->val); 40 } 41 nodeQueue.pop(); //不要忘了 42 } 43 reverse(ret.begin(), ret.end()); 44 return ret; 45 } 46 };
上面写的可能结果是对的,但是好像不是题目本来的意思,下面用dfs重新写一遍
1 public class Solution { 2 public List<List<Integer>> levelOrderBottom(TreeNode root) { 3 List<List<Integer>> ret = new ArrayList<List<Integer>>(); 4 dfs(ret, root, 0); 5 Collections.reverse(ret); 6 return ret; 7 } 8 9 public void dfs(List<List<Integer>> ret, TreeNode root, int dep){ 10 if(root == null) 11 return; 12 if(ret.size() <= dep){ 13 List<Integer> tmp = new ArrayList<Integer>(); 14 ret.add(tmp); 15 } 16 ret.get(dep).add(root.val); 17 if(root.left != null) dfs(ret, root.left, dep+1); 18 if(root.right != null) dfs(ret, root.right, dep+1); 19 } 20 }