【leetcode 刷题日记】22-二叉树的中序遍历(C++)

二叉树的中序遍历

递归思路

中序遍历

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> res;
    vector<int> inorderTraversal(TreeNode* root) {
        if(root == NULL){
            return res;
        }
        if(root->left) inorderTraversal(root->left);//左
        res.push_back(root->val);//中
        if(root->right) inorderTraversal(root->right);//右
        return res;
    }

};

前序遍历

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int>res;
    vector<int> preorderTraversal(TreeNode* root) 
    {
       if(root)
      {
          res.push_back(root->val);
          preorderTraversal(root->left);
           preorderTraversal(root->right);
      }
      return res;
    }
};


后序遍历

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
vector<int>res;
    vector<int> postorderTraversal(TreeNode* root) {
        if(root)
        {
            postorderTraversal(root->left);
            postorderTraversal(root->right);
            res.push_back(root->val);
        }
        return res;
    }
};
发布了34 篇原创文章 · 获赞 24 · 访问量 1998

猜你喜欢

转载自blog.csdn.net/fengshiyu1997/article/details/105026482