码迷,mamicode.com
首页 > 其他好文 > 详细

145. Binary Tree Postorder Traversal

时间:2018-03-03 20:32:51      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:space   log   null   ace   int   treenode   res   tree   一个   

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

For example:
Given binary tree [1,null,2,3],

   1
         2
    /
   3

思路: 借助于一个栈,依次将根节点的右子节点和左子节点压入栈中。如果一个节点为叶子节点,或者前一个出栈的元素为当前栈顶节点的子节点,则出栈。

 vector<int> postorderTraversal(TreeNode* root) {
         vector<int> res;
         stack<TreeNode*> _stack;
         TreeNode *cur=root;
         TreeNode *pre=NULL;
         if(cur!=NULL)
             _stack.push(cur);
         while(!_stack.empty())
         {
             cur=_stack.top();
             if((cur->left==NULL&&cur->right==NULL)||(pre&&(cur->left==pre||cur->right==pre)))
             {
                 res.push_back(cur->val);
                 pre=cur;
                 _stack.pop();
             }
             else
             {
                 if(cur->right)
                     _stack.push(cur->right);
                 if(cur->left)
                     _stack.push(cur->left);
             }
         }
        return res;
    }

 

145. Binary Tree Postorder Traversal

标签:space   log   null   ace   int   treenode   res   tree   一个   

原文地址:https://www.cnblogs.com/zhaoyaxing/p/8502683.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!