leetcode145. 二叉树的后序遍历(超级通俗易懂的迭代法)

tech2022-07-05  253

给定一个二叉树,返回它的 后序 遍历。 示例:

输入: [1,null,2,3] 输出: [3,2,1]

/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<int> postorderTraversal(TreeNode* root) { vector<int> vecRes; if(root==nullptr) return vecRes; stack<TreeNode*> s; s.push(root); while(!s.empty()) { TreeNode * pNode = s.top(); s.pop(); if(pNode) { s.push(pNode); s.push(nullptr); if(pNode->right) s.push(pNode->right); if(pNode->left) s.push(pNode->left); } else { vecRes.push_back(s.top()->val); s.pop(); } } return vecRes; } };
最新回复(0)