题解 | #实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
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> > res;
vector<int> preorder, inorder, postorder;
vector<vector<int> > threeOrders(TreeNode* root) {
preOrder(root);
inOrder(root);
postOrder(root);
res.push_back(preorder);
res.push_back(inorder);
res.push_back(postorder);
return res;
}
void preOrder(TreeNode* root) {
if (!root) return;
preorder.push_back(root->val); // 访问根结点
preOrder(root->left); // 访问左子树
preOrder(root->right); // 访问右子树
}
void inOrder(TreeNode* root) {
if (!root) return;
inOrder(root->left); // 访问左子树
inorder.push_back(root->val); // 访问根结点
inOrder(root->right); // 访问右子树
}
void postOrder(TreeNode* root) {
if (!root) return;
postOrder(root->left); // 访问左子树
postOrder(root->right); // 访问右子树
postorder.push_back(root->val); // 访问根结点
}
};