题解 | #二叉树的后序遍历#
二叉树的后序遍历
https://www.nowcoder.com/practice/1291064f4d5d4bdeaefbf0dd47d78541
1.用深搜来遍历树并储存结果( dfs() )
(1).二叉树顺序为左右根(8~10行)
(2).并存到post中(5,10行)
(3).遍历到空节点就跳出(7行)
2.输出结果( postorderTraversal() )
(1).调用dfs(),将结果存在post中(5,14行)
(2).返回结果(16行)
#include <vector>
class Solution {
public:
vector<int> post={};
void dfs(TreeNode* root){
if (root==NULL) return;
dfs(root->left);
dfs(root->right);
post.push_back(root->val);
}
vector<int> postorderTraversal(TreeNode* root) {
// write code here
dfs(root);
return post;
}
};
查看7道真题和解析
联想公司福利 1477人发布