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

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

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

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
#include <ios>
class Solution {
private:
  vector<vector<int>> fin_ans;
  vector<int> preans, midans, sufans;
  void pre(TreeNode* root){//---------前序遍历 根左右
    preans.push_back(root->val);//------先存根
    if (root->left != nullptr)//-----------能往左走就往左走
      pre(root->left);
    if (root->right != nullptr)//---------左边走完再走右边
      pre(root->right);
  }
  void mid(TreeNode* root){//---------中序遍历 左跟右
    if (root->left != nullptr)
      mid(root->left);
    midans.push_back(root->val);
    if (root->right != nullptr)
      mid(root->right);
  }
  void suf(TreeNode* root){//----------后续遍历 左右跟
    if (root->left != nullptr)
      suf(root->left);
    if (root->right != nullptr)
      suf(root->right);
    sufans.push_back(root->val);
  }
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * @brief 如题所诉😘
     * 
     * @param root TreeNode类 the root of binary tree
     * @return int整型vector<vector<>>
     */
    vector<vector<int> > threeOrders(TreeNode* root) {
        // write code here
      if (root != nullptr){
      pre(root); mid(root); suf(root);
      }
      fin_ans.push_back(preans);
      fin_ans.push_back(midans);
      fin_ans.push_back(sufans);
      return fin_ans;
    }
};

#写题解领奖励#
全部评论

相关推荐

一表renzha:不是你说是南通我都没往那方面想,人家真是想表达那个意思吗?
点赞 评论 收藏
分享
07-19 13:28
长沙学院 Java
程序员小白条:你有面试就有希望,没面试自然就没希望,到时候就知道了,你问别人也没啥用处的
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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