LeetCode[107] Binary Tree Level Order Traversal II
107. Binary Tree Level Order Traversal II
難度:Medium
Python:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
def dfs(root, depth, result):
if root == None:
return
if depth == len(result):
result.append([])
result[depth].append(root.val)
dfs(root.left, depth+1, result)
dfs(root.right, depth+1, result)
class Solution:
def levelOrderBottom(self, root: Optional[TreeNode]) -> List[List[int]]:
result = []
dfs(root,0,result)
result.reverse()
return result
C++:
void dfs(TreeNode* root, int depth, vector<vector<int>>& result) {
if(root == nullptr){
return;
}
if(depth == result.size()) {
result.push_back({});
}
result[depth].push_back(root->val);
dfs(root->left,depth+1,result);
dfs(root->right, depth+1,result);
}
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> result;
dfs(root, 0, result);
reverse(begin(result), end(result));
return result;
}
};
本部落格所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 LuYee6813's Blog | 技術分享!