欢迎大家阅读参考,如有错误或疑问请留言纠正,谢谢
107 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]
]
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ //方法一:BFS struct Node { TreeNode *node; int level; Node(TreeNode *n , int l) : node(n) , level(l) {} }; class Solution { vector<vector<int>> ans; public: vector<vector<int> > levelOrderBottom(TreeNode *root) { ans.clear(); if(root == NULL) return ans; vector<int> temp; int Curlevel = -1; queue<Node> q; q.push( Node(root , 1) ); while(!q.empty()) { Node nodeQ = q.front(); q.pop(); if(nodeQ.node->left) q.push( Node(nodeQ.node->left , nodeQ.level+1) ); if(nodeQ.node->right) q.push( Node(nodeQ.node->right , nodeQ.level+1) ); if(Curlevel != nodeQ.level) { if(Curlevel != -1) ans.push_back(temp); temp.clear(); temp.push_back(nodeQ.node->val); Curlevel = nodeQ.level; } else temp.push_back(nodeQ.node->val); } ans.push_back(temp); reverse(ans.begin() , ans.end()); return ans; } };
//方法二:DFS class Solution { vector<vector<int>> ans; public: void levelOrderUtil (TreeNode *root , int depth) { if(root==NULL) return; if(ans.size() > depth) ans[depth].push_back(root->val); else { vector<int> a; a.push_back(root->val); ans.push_back(a); } levelOrderUtil( root->left , depth+1 ); levelOrderUtil( root->right , depth+1 ); } vector<vector<int> > levelOrderBottom(TreeNode *root) { ans.clear(); levelOrderUtil( root , 0); reverse(ans.begin(), ans.end()); return ans; } };
时间: 2024-12-20 00:36:42