其他分享
首页 > 其他分享> > ​LeetCode刷题实战145:二叉树的后序遍历

​LeetCode刷题实战145:二叉树的后序遍历

作者:互联网

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。今天和大家聊的问题叫做 二叉树的后序遍历,我们先来看题面:

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

题意

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

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

 

解题

上一题目 用了递归方法,这题也可以继续用递归方法,不过这次我们换个方法来实现,这样才能学到更多有用的知识 。这次我们用利用栈+set辅助完成,具体实现看下面代码,也做了完整的注释了 。

 

/**
 * 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> result;
    set<TreeNode*> visited;//用于标记已经访问过的节点
    stack<TreeNode*> myStack;//辅助栈,用于保留现场
    while (root != NULL || !myStack.empty()) {
      if (root != NULL) {
        myStack.push(root);//栈先保护根节点的现场
        visited.insert(root);//标记根节点已访问
        if (root->right) {//右子树不为空,保护右子树现场
          myStack.push(root->right);
        }
        root = root->left;//现场转移至左子树
        continue;
      }
      root = myStack.top();//恢复现场
      myStack.pop();
      while (visited.find(root) != visited.end()) {//如果这个节点已经访问过(根节点)
        result.push_back(root->val);
        if (!myStack.empty()) {
          root = myStack.top();//再恢复现场
          myStack.pop();
        }
        else {
          root == NULL;
                    return result;
        }
      }
    }
    return result;
  }
};

好了,今天的文章就到这里

 

标签:145,TreeNode,right,二叉树,myStack,NULL,root,LeetCode,result
来源: https://blog.51cto.com/u_13294304/2954099