题解 | #二叉树的中序遍历# (递归)

二叉树的中序遍历

https://www.nowcoder.com/practice/0bf071c135e64ee2a027783b80bf781d

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* 方法一:使用递归法,基本的中序遍历思想,就可以求出;注意点:首地址为空的判读,属于特殊情况;
* };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return int整型vector
     */
    vector<int> inorderTraversal(TreeNode* root) {
        // write code here
        vector<int> result;
        if (root == nullptr)
          return result;
          
        InorderTraversal(root, result);
        return result;
    }

    void InorderTraversal(TreeNode* root, vector<int>& result) {
      if (root->left != nullptr)
        InorderTraversal(root->left, result);
      
      result.push_back(root->val);

      if (root->right != nullptr)
        InorderTraversal(root->right, result);
    }
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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