题解 | #实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
http://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类 the root of binary tree
* @return int整型vector<vector<>>
*/
vector<vector<int> > threeOrders(TreeNode* root) {
// write code here
vector<vector<int> > res(3);
preOrder(root,res[0]);
inOrder(root,res[1]);
posOrder(root,res[2]);
return res;
}
vector<int> preOrder(TreeNode* root,vector<int>& res){
if(root == nullptr) return {};
res.push_back(root->val);
preOrder(root->left, res);
preOrder(root->right, res);
return res;
}
vector<int> inOrder(TreeNode* root,vector<int>& res){
if(root == nullptr) return {};
inOrder(root->left, res);
res.push_back(root->val);
inOrder(root->right, res);
return res;
}
vector<int> posOrder(TreeNode* root,vector<int>& res){
if(root == nullptr) return {};
posOrder(root->left, res);
posOrder(root->right, res);
res.push_back(root->val);
return res;
}
};