华为机试复习--树

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);
    }
};

posted @ 2021-03-24 15:58  Jorgensen  阅读(43)  评论(0编辑  收藏  举报
#site_nav_under { display: none; } .c_ad_block, .ad_text_commentbox { display: none; margin: 0; padding: 0; } #ad_under_google { height: 0; overflow: hidden; } #ad_under_google a { display: none; }