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

二叉树的中序遍历

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;
    }
};
全部评论

相关推荐

程序员花海:实习和校招简历正确格式应该是教育背景+实习+项目经历+个人评价 其中项目经历注意要体现业务 实习经历里面的业务更是要自圆其说 简历模板尽可能保持干净整洁 不要太花哨的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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