107. Sequence Traversal of Binary Tree II
Title description
Given a binary tree, return the bottom-up traversal of its node values. (That is, from the layer where the leaf node is located to the layer where the root node is located, traversing from left to right layer by layer)
For example:
given a binary tree [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
Return its bottom-up sequence traversal as:
[
[15,7],
[9,20],
[3]
]
answer:
This question is also two ways of thinking:
- Reference binary tree traversal sequence , the normal sequence through the results to reverse
- Do not use reverse order, this is a bit troublesome.
I do not write in reverse order, in the binary tree traversal sequence , based on the results returned in reverse order on the line.
The following describes how to write in non-reverse order:
- Find the height of the binary tree
total_dep
- The resulting array
ret
is set tototal_dep
an empty array - Recursive process, assume the current depth of recursion
dep
(starting at 1), the layer node belongs toret
the firsttotal_dep - dep
row
Time complexity: O (n) O(n)O ( n )
Extra space complexity: O (n) O(n)O ( n )
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> ret;
int total_dep;
int depth( TreeNode* root ) {
if ( !root ) return 0;
return 1 + max( depth( root->left ), depth( root->right) );
}
void dfs( TreeNode* root, int dep ) {
if ( !root ) return;
ret[total_dep - dep].emplace_back( root->val );
dfs( root->left, dep + 1 );
dfs( root->right, dep + 1 );
}
vector<vector<int>> levelOrderBottom(TreeNode* root) {
total_dep = depth( root );
for ( int i = 0; i < total_dep; ++i )
ret.emplace_back( vector<int>{
} );
dfs( root, 1 );
return ret;
}
};
/*
时间:0ms,击败:100.00%
内存:11.4MB,击败:71.52%
*/
Of course, the reference binary tree traversal sequence method , a new array is inserted into ret
the head may be:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> ret;
void dfs( TreeNode* root, int dep ) {
if ( !root ) return;
if ( ret.size() < dep )
ret.insert( ret.begin(), vector<int>{
} );
ret[ret.size() - dep].emplace_back( root->val );
dfs( root->left, dep + 1 );
dfs( root->right, dep + 1 );
}
vector<vector<int>> levelOrderBottom(TreeNode* root) {
dfs( root, 1 );
return ret;
}
};
/*
时间:28ms,击败:7.87%
内存:12.3MB,击败:6.92%
*/
But the efficiency is touching. . .