分别调用三个函数,分别先序遍历、中序遍历、后序遍历。前序遍历先向结果数组 ret 中插入根节点值,然后递归调用左、右子树的前序遍历函数,中序遍历和后序遍历类似。代码如下:
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ class Solution { vector<vector<int> > ret; public: /** * * @param root TreeNode类 the root of binary tree * @return int整型vector<vector<>> */ void preorder(TreeNode *root) { if(root == NULL) return; ret[0].push_back(root->val); preorder(root->left); preorder(root->right); } void inorder(TreeNode *root) { if(root == NULL) return; inorder(root->left); ret[1].push_back(root->val); inorder(root->right); } void afterorder(TreeNode *root) { if(root == NULL) return; afterorder(root->left); afterorder(root->right); ret[2].push_back(root->val); } vector<vector<int> > threeOrders(TreeNode* root) { ret.resize(3); preorder(root); inorder(root); afterorder(root); return ret; } };
全部评论
(0) 回帖