华为机试复习--树
NC45 实现二叉树先序,中序和后序遍历
题目描述
分别按照二叉树先序,中序和后序打印所有的节点。
示例1
输入
{1,2,3}
返回值
[[1,2,3],[2,1,3],[2,3,1]]
/**
* 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<int> pre;
vector<int> in;
vector<int> post;
vector<vector<int> > threeOrders(TreeNode* root) {
// write code here
if(root==NULL)
return vector<vector<int>>{pre,in,post};
preOrder(root);
inOrder(root);
postOrder(root);
vector<vector<int>> ans;
ans.push_back(pre);
ans.push_back(in);
ans.push_back(post);
return ans;
}
void preOrder(TreeNode* root) {
if (root == NULL) return;
pre.push_back(root->val);
preOrder(root->left);
preOrder(root->right);
}
void inOrder(TreeNode* root) {
if (root == NULL) return;
inOrder(root->left);
in.push_back(root->val);
inOrder(root->right);
}
void postOrder(TreeNode* root) {
if (root == NULL) return;
postOrder(root->left);
postOrder(root->right);
post.push_back(root->val);
}
};