LeetCode145. 二叉树的后序遍历

//145. 二叉树的后序遍历
//正常递归实现,比较简单
class Solution {
public:
  vector<int> ans;
  void dfs(TreeNode* node) {
    if (node == nullptr) return;
    dfs(node->left);
    dfs(node->right);
    ans.emplace_back(node->val);
  }
  vector<int> postorderTraversal(TreeNode* root) {
    dfs(root);
    return ans;
  }
};
//使用stack,有点绕,建议多想想,手动狗头
class Solution {
public:
  vector<int> postorderTraversal(TreeNode* root) {
    vector<int>ans;
    if (root == nullptr) return ans;
    auto node = root;
    stack<TreeNode*> stk;
    TreeNode* ptr;
    while (node != nullptr || stk.size()) {
      while (node != nullptr) {
        stk.push(node);
        node = node->left;
      }
      node = stk.top(); stk.pop();
      if (node->right == nullptr || node->right == ptr) {
        ans.emplace_back(node->val);
        ptr = node;
        node = nullptr;
      }
      else {
        stk.emplace(node);
        node = node->right;
      }
    }
    return ans;
  }
};
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页