您的当前位置:首页正文

leetcode 145 Binary Tree Postorder Traversal

2024-11-07 来源:个人技术集锦

Given a binary tree, return the postorder traversal of its nodes' values.

For example:
Given binary tree {1,#,2,3},

   1
    \
     2
    /
   3

return [3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?

 to see which companies asked this question

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
		if(root==NULL) return res;
		stack<TreeNode*> sta;

		sta.push(root);

		while(!sta.empty()) {
			TreeNode *top = sta.top();
			if(top->left!=NULL) {
				sta.push(top->left);
				top->left = NULL;
			} else if(top->right!=NULL) {
				sta.push(top->right);
				top->right = NULL;
			} else {
				sta.pop();
				res.push_back(top->val);
			}
		}

		return res;
    }
};




Top