[LeetCode]145 二叉树后序遍历

来源:互联网 发布:淘宝刷单兼职91lingla 编辑:程序博客网 时间:2024/05/28 05:13

Binary Tree Postorder Traversal(二叉树后序遍历)

【难度:Medium】
Given a binary tree, return the postorder traversal of its nodes’ values.

For example:
Given binary tree {1,#,2,3},
这里写图片描述
return [3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?
使用迭代而不是递归的方法后序遍历二叉树


解题思路

整体思路与LeetCode 94题和144题一致,但在后序遍历这里采取的是先走根节点,再走右子树,再走左子树,最后将结果顺序反转来得到后序遍历的答案,因为这样比较方便。


c++代码如下:

//迭代方法/** * 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> v;        stack<TreeNode*> s;        TreeNode* cur = root;        while (cur || !s.empty()) {            if (cur) {                s.push(cur);                v.push_back(cur->val);                cur = cur->right;            } else {                cur = s.top()->left;                s.pop();            }        }        reverse(v.begin(),v.end());        return v;    }};
//递归方法/** * 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> v;        if (!root)            return v;        vector<int> left = postorderTraversal(root->left);        if (!left.empty()) {            for (auto i:left)                v.push_back(i);        }        vector<int> right = postorderTraversal(root->right);        if (!right.empty()) {            for (auto i:right)                v.push_back(i);        }        v.push_back(root->val);        return v;    }};
0 0
原创粉丝点击