zoukankan      html  css  js  c++  java
  • 华为机试复习--树

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

  • 相关阅读:
    前端资源分享
    解决COM组件80070005错误
    【迁移】—Entity Framework实例详解 转
    IIS错误处理集合
    疯狂蚂蚁框架搭建
    MSSQL日期格式化
    一句SQL实现获取自增列操作
    mongodb 性能篇
    mongodb管理篇
    mongodb高级应用
  • 原文地址:https://www.cnblogs.com/Jorgensen/p/14573891.html
Copyright © 2011-2022 走看看