leetcode刷题, 总结,记录,备忘145

原创 2015年07月09日 15:27:07

leetcode145

Binary Tree Postorder Traversal

 

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?

二叉树后序遍历,用递归的确很简单,就不讨论了。这是我做的第一道hard题,,竟然一次过,顿时感觉666,可是事后一想其实也没那么难,通过率还是很高的,试用stack从根节点开始,先入栈,然后弹栈,将值域放入vector中,然后先将左节点入栈,再将右节点入栈,开始循环,最终得到将后序遍历的结果反序放入vector中的结果,然后只要反排一下数组就搞定啦,,,是不是很简单呢,,今天一次就过有点得瑟,上个图秀下。

好了,上代码

/**
 * 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) {
        stack<TreeNode*> st;
        vector<int> vi;
        TreeNode * temp;
        if (root == NULL)
        return vector<int>();
        st.push(root);
        while (!st.empty())
        {
            temp = st.top();
            st.pop();
            vi.push_back(temp->val);
            if(temp->left)
            st.push(temp->left);
            if(temp->right)
            st.push(temp->right);
        }
        
        return vector<int>(vi.rbegin(), vi.rend());
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode(145)Binary Tree Postorder Traversal

题目如下: Given a binary tree, return the postorder traversal of its nodes' values. 1 \ 2 ...

LeetCode145 Binary Tree Postorder Traversal Java题解(递归 迭代)

题目: Given a binary tree, return the postorder traversal of its nodes' values. For example: ...

leetcode刷题,总结,记录,备忘 201

leetcode201Bitwise AND of Numbers Range Given a range [m, n] where 0 For example, given the rang...

leetcode刷题,总结,记录,备忘 223

leetcode223 Find the total area covered by two rectilinear rectangles in a 2D plane. Each re...

leetcode刷题, 总结,记录, 备忘142

leetcode142 Given a linked list, return the node where the cycle begins. If there is no cycle, retu...

leetcode刷题,总结,记录,备忘 313

leetcode313Super Ugly Number Write a program to find the nth super ugly number. Super ugly n...

leetcode刷题,总结,记录,备忘300

leetcode300,Longest Increasing Subsequence Given an unsorted array of integers, find the length...

leetcode刷题,总结,记录,备忘 312

leetcode312Burst Balloons Given n balloons, indexed from 0 to n-1. Each balloon is painted with a...

leetcode刷题,总结,记录,备忘 39

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C wher...

leetcode刷题,总结,记录,备忘 88

leetcode88,Merge Sorted Array Given two sorted integer arrays nums1 and nums2, merge nums2 into nu...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode刷题, 总结,记录,备忘145
举报原因:
原因补充:

(最多只允许输入30个字)