题解 | #二叉树的中序遍历#

二叉树的中序遍历

http://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:
    vector<int> inorderTraversal(TreeNode* root) {
      std::vector<int> res;
      inorder(root, res);
      return res;
    }
  private:
    void inorder(TreeNode *root, std::vector<int> &res) {
      if (root == nullptr) {
        return ;
      }
      inorder(root->left, res);
      res.push_back(root->val);
      inorder(root->right, res);
    }
};

迭代:稍微有点复杂
需要好好消化

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
      std::vector<int> res;
      std::stack<TreeNode *> stack_;
      
      while (root || !stack_.empty()) {
        while (root) {
          stack_.push(root);
          root = root->left;
        }
        TreeNode *tmp = stack_.top();
        stack_.pop();
        res.push_back(tmp->val);
        root = tmp->right;
      }
      
      return res;
    }
};
全部评论

相关推荐

看网上说华为1145每个人都会收到,请问华为1145是什么东西
老黑奴:面试如果通过当天晚上11:45会收到面试反馈邮件
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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