题解 | #实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
https://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ class Solution { public: vector<vector<int>> ans; inline void visit(int num, int index) { ans[index].push_back(num); } void preorder(TreeNode* root) { if (NULL == root) { return; } visit(root->val, 0); preorder(root->left); preorder(root->right); } void inorder(TreeNode* root) { if (NULL == root) { return; } inorder(root->left); visit(root->val, 1); inorder(root->right); } void postorder(TreeNode* root) { if (NULL == root) { return; } postorder(root->left); postorder(root->right); visit(root->val, 2); } /** * * @param root TreeNode类 the root of binary tree * @return int整型vector<vector<>> */ vector<vector<int> > threeOrders(TreeNode* root) { vector<int> tmp; tmp.clear(); ans.push_back(tmp); ans.push_back(tmp); ans.push_back(tmp); preorder(root); inorder(root); postorder(root); return ans; } };