题解 | #实现二叉树先序,中序和后序遍历#

实现二叉树先序,中序和后序遍历

https://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362

/**
 * struct TreeNode {
 *  int val;
 *  struct TreeNode *left;
 *  struct TreeNode *right;
 * };
 */

class Solution {
  public:
    vector<vector<int>> ans;
    inline void visit(int num, int index) {
        ans[index].push_back(num);
    }
    void preorder(TreeNode* root) {
        if (NULL == root) {
            return;
        }
        visit(root->val, 0);
        preorder(root->left);
        preorder(root->right);

    }
    void inorder(TreeNode* root) {
        if (NULL == root) {
            return;
        }

        inorder(root->left);
        visit(root->val, 1);
        inorder(root->right);

    }
    void postorder(TreeNode* root) {
        if (NULL == root) {
            return;
        }

        postorder(root->left);
        postorder(root->right);
        visit(root->val, 2);

    }
    /**
     *
     * @param root TreeNode类 the root of binary tree
     * @return int整型vector<vector<>>
     */
    vector<vector<int> > threeOrders(TreeNode* root) {
        vector<int> tmp;
        tmp.clear();
        ans.push_back(tmp);
        ans.push_back(tmp);
        ans.push_back(tmp);

        preorder(root);
        inorder(root);
        postorder(root);
        return ans;
    }
};

全部评论

相关推荐

Z_eus:别打招呼直接发你的优势
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务