NC45实现二叉树先序,中序和后序遍历(递归)

NC45实现二叉树先序,中序和后序遍历(递归)

- 1、题目描述:
图片说明

- 2、题目链接:
https://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362?tpId=117&tqId=37819&rp=1&ru=%2Factivity%2Foj&qru=%2Fta%2Fjob-code-high%2Fquestion-ranking&tab=answerKey

-3、 设计思想:
图片说明

-5、代码:
c++版本:

/**
 * 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;//存储后序遍历结果
         /*先序遍历*/
     void preOrderRecur(TreeNode *root) {
        if (root == nullptr) return;
        pre.push_back(root->val);//根
        preOrderRecur(root->left);//左
        preOrderRecur(root->right);//右
    }
     /*中序遍历*/
     void inOrderRecur(TreeNode *root) {
        if (root == nullptr) return;
        inOrderRecur(root->left);//左
        in.push_back(root->val);//根
        inOrderRecur(root->right);//右
    }
     /*后序遍历*/
     void posOrderRecur(TreeNode *root) {
        if (root == nullptr) return;
        posOrderRecur(root->left);//左
        posOrderRecur(root->right);//右
        post.push_back(root->val);//根
    }
    vector<vector<int> > threeOrders(TreeNode* root) {
        // write code here
        vector<vector<int>>res;//用于返回最终的结果
        if(root == nullptr) return res;
        preOrderRecur(root);//先序遍历
        inOrderRecur(root);//中序遍历
        posOrderRecur(root);//后序遍历
        res.push_back(pre);//将先序遍历放进res
        res.push_back(in);//将中序遍历放进res
        res.push_back(post);//将后序遍历放进res
        return res;
    }
};

Java版本:

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 the root of binary tree
     * @return int整型二维数组
     */
    ArrayList<Integer> pr

剩余60%内容,订阅专栏后可继续查看/也可单篇购买

前端岗位面试真题宝典 文章被收录于专栏

本面试宝典均来自校招面试题目大数据进行的整理

全部评论

相关推荐

12-14 11:43
黑龙江大学 Java
用微笑面对困难:确实比较烂,可以这么修改:加上大学的qs排名,然后大学简介要写一些,然后硕士大学加大加粗,科研经历第一句话都写上在复旦大学时,主要负责xxxx,简历左上角把学校logo写上,建议用复旦大学的简历模板
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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