LeetCode Summary
  • Introduction
  • DP, 动态规划类
    • Best Time to Buy and Sell Stock III 题解
    • Best Time to Buy and Sell Stock 题解
    • Climbing Stairs 题解
    • Decode Ways 题解
    • Distinct Subsequences 题解
    • Edit Distance 题解
    • Interleaving String 题解
    • Longest Palindromic Substring 题解
    • Maximum Product Subarray 题解
    • Maximum Subarray 题解
    • Minimum Path Sum 题解
    • Palindrome Partitioning 题解
    • Palindrome Partitioning II 题解
    • Scramble String 题解
    • Triangle 题解
    • Unique Binary Search Trees 题解
    • Unique Paths II 题解
    • Word Break 题解
    • Word Break II 题解
  • list, 链表相关
    • Add Two Numbers 题解
    • Convert Sorted List to Binary Search Tree 题解
    • Copy List with Random Pointer 题解
    • Insertion Sort List 题解
    • LRU Cache 题解
    • Linked List Cycle 题解
    • Linked List Cycle II 题解
    • Merge Two Sorted Lists 题解
    • Merge k Sorted Lists 题解
    • Partition List 题解
    • Remove Duplicates from Sorted List 题解
    • Remove Duplicates from Sorted List II 题解
    • Remove Nth Node From End of List 题解
    • Reorder List 题解
    • Reverse Linked List II 题解
    • Reverse Nodes in k-Group 题解
    • Rotate List 题解
    • Sort List 题解
    • Swap Nodes in Pairs 题解
  • binary tree, 二叉树相关
    • Balanced Binary Tree 题解
    • Binary Tree Inorder Traversal 题解
    • Binary Tree Level Order Traversal 题解
    • Binary Tree Level Order Traversal II 题解
    • Binary Tree Maximum Path Sum 题解
    • Binary Tree Postorder Traversal 题解
    • Binary Tree Preorder Traversal 题解
    • Binary Tree Zigzag Level Order Traversal 题解
    • Construct Binary Tree from Inorder and Postorder Traversal 题解
    • Construct Binary Tree from Preorder and Inorder Traversal 题解
    • Convert Sorted List to Binary Search Tree 题解
    • Flatten Binary Tree to Linked List 题解
    • Maximum Depth of Binary Tree 题解
    • Minimum Depth of Binary Tree 题解
    • Path Sum 题解
    • Path Sum II 题解
    • Populating Next Right Pointers in Each Node 题解
    • Populating Next Right Pointers in Each Node II 题解
    • Recover Binary Search Tree 题解
    • Same Tree 题解
    • Sum Root to Leaf Numbers 题解
    • Symmetric Tree 题解
    • Unique Binary Search Trees 题解
    • Unique Binary Search Trees II 题解
    • Validate Binary Search Tree 题解
  • sort, 排序相关
    • 3Sum Closest 题解
    • 3Sum 题解
    • 4Sum 题解
    • Insert Interval 题解
    • Longest Consecutive Sequence 题解
    • Merge Intervals 题解
    • Merge Sorted Array 题解
    • Remove Duplicates from Sorted Array 题解
    • Remove Duplicates from Sorted Array II 题解
    • Sort Colors 题解
    • Two Sum 题解
  • search, 搜索相关
    • First Missing Positive 题解
    • Find Minimum in Rotated Sorted Array 题解
    • Find Minimum in Rotated Sorted Array II 题解
    • Median of Two Sorted Arrays 题解
    • Search Insert Position 题解
    • Search a 2D Matrix 题解
    • Search for a Range 题解
    • Search in Rotated Sorted Array 题解
    • Search in Rotated Sorted Array II 题解
    • Single Number 题解
    • Single Number II 题解
  • math, 数学类相关
    • Add Binary 题解
    • Add Two Numbers 题解
    • Divide Two Integers 题解
    • Gray Code 题解
    • Integer to Roman 题解
    • Multiply Strings 题解
    • Palindrome Number 题解
    • Plus One 题解
    • [Pow(x, n) 题解](math/Pow(x,-n).md)
    • Reverse Integer 题解
    • Roman to Integer 题解
    • [Sqrt(x) 题解](math/Sqrt(x).md)
    • [String to Integer (atoi) 题解](math/String-to-Integer-(atoi).md)
    • Valid Number 题解
  • string, 字符串处理相关
    • Anagrams 题解
    • Count and Say 题解
    • Evaluate Reverse Polish Notation 题解
    • [Implement strStr() 题解](string/Implement-strStr().md)
    • Length of Last Word 题解
    • Longest Common Prefix 题解
    • Longest Palindromic Substring 题解
    • Longest Substring Without Repeating Characters 题解
    • Longest Valid Parentheses 题解
    • Minimum Window Substring 题解
    • Regular Expression Matching 题解
    • Reverse Words in a String 题解
    • Simplify Path 题解
    • Text Justification 题解
    • Valid Parentheses 题解
    • Wildcard Matching 题解
    • ZigZag Conversion 题解
  • combination and permutation, 排列组合相关
    • Combinations 题解
    • Combination Sum 题解
    • Combination Sum II 题解
    • Letter Combinations of a Phone Number 题解
    • Next Permutation 题解
    • Palindrome Partitioning 题解
    • Permutation Sequence 题解
    • Permutations 题解
    • Permutations II 题解
    • Subsets 题解
    • Subsets II 题解
    • Unique Paths 题解
  • matrix, 二维数组, 矩阵相关
    • Rotate Image 题解
    • Set Matrix Zeroes 题解
    • Spiral Matrix 题解
    • Spiral Matrix II 题解
    • Maximal Rectangle 题解
  • 回溯, BFS/DFS
    • Clone Graph 题解
    • Generate Parentheses 题解
    • N-Queens 题解
    • N-Queens II 题解
    • Restore IP Addresses 题解
    • Sudoku Solver 题解
    • Surrounded Regions 题解
    • Word Ladder 题解
    • Word Ladder II 题解
    • Word Search 题解
  • greedy, 贪心
    • Best Time to Buy and Sell Stock II 题解
    • Jump Game 题解
    • Jump Game II 题解
  • 其他
    • Candy 题解
    • Container With Most Water 题解
    • Gas Station 题解
    • Gray Code 题解
    • Max Points on a Line 题解
    • [Pascal's Triangle 题解](others/Pascal's-Triangle.md)
    • [Pascal's Triangle II 题解](others/Pascal's-Triangle-II.md)
    • Remove Element 题解
    • Trapping Rain Water 题解
Powered by GitBook
On this page
  • 思路一: 直接递归
  • 思路二: 非递归. 仿造先序,因为先序的非递归很好写.
  • 思路三:传统方法
  • 思路四:改进的传统方法
  • 思路五:Morris遍历

Was this helpful?

  1. binary tree, 二叉树相关

Binary Tree Postorder Traversal 题解

PreviousBinary Tree Maximum Path Sum 题解NextBinary Tree Preorder Traversal 题解

Last updated 5 years ago

Was this helpful?

题目来源:

> 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?

解题思路:

下文用了5种方法实现了对二叉树进行后序遍历。

思路一: 直接递归

    void postRecursion(TreeNode * root, vector<int> &path)
    {
        if(root == NULL) return;
        if(root->left != NULL)
            postRecursion(root->left, path);
        if(root->right != NULL)
            postRecursion(root->right, path);
        path.push_back(root->val);
    }

    vector<int> postorderTraversal(TreeNode *root) 
    {
        vector<int> result;
        postRecursion(root, result);
        return move(result);
    }

思路二: 非递归. 仿造先序,因为先序的非递归很好写.

(来自寝室哥们ZZ大神的思路)

先序: `中左右` 
后序: `左右中` 

发现 先序.reverse = 右左中 将右左交换就得到左右中. 即将原来的先序变通下就有了下面的算法.

    vector<int> postFakePre(TreeNode * root)
    {
        stack<TreeNode*> stacks;
        stacks.push(root);
        vector<int> result;
        while(! stacks.empty())
        {
            auto node = stacks.top();
            result.push_back(node->val); stacks.pop();
            //pre: push right then left, 
            //fake pre: push left, then right
            if(node->left != NULL)
                stacks.push(node->left);
            if(node->right != NULL)
                stacks.push(node->right);
        }
        std::reverse(result.begin(), result.end());
        return move(result);
    }

思路三:传统方法

用一个指针last记录上一次访问的节点来区分右孩纸是否已经访问过了该回归到父节点。代码如下

    vector<int> postNormal(TreeNode * root)
    {
        stack<TreeNode*> stacks;
        vector<int> result;
        TreeNode* last = NULL, * cur = root;
        while(true)
        {
            if(cur != NULL)//go to left most
            {
                stacks.push(cur);
                cur = cur->left;
            }else //leaf node
            {
                auto peak = stacks.top();
                if(peak->right != NULL && peak->right != last) // right child has not been visited
                {
                    cur = peak->right;
                }else{
                    result.push_back(peak->val);
                    stacks.pop();
                    last = peak;
                    if(stacks.empty()) 
                        break;
                }
            }
        }
        return move(result);
    }

思路四:改进的传统方法

下面的方法来自网络(但忘了具体出处了). 比较好理解。

> 要保证根结点在左孩子和右孩子访问之后才能访问,因此对于任一结点P,先将其入栈。 如果P不存在左孩子和右孩子,则可以直接访问它;或者P存在左孩子或者右孩子,但是其左孩子和右孩子都已被访问过了,则同样可以直接访问该结点。 若非上述两种情况,则将P的右孩子和左孩子依次入栈,这样就保证了每次取栈顶元素的时候,左孩子在右孩子前面被访问,左孩子和右孩子都在根结点前面被访问。

代码如下:

    vector<int> postNormalBetter(TreeNode * root)
    {
        stack<TreeNode*> stacks;
        vector<int> result;
        TreeNode* last = NULL;
        stacks.push(root);
        while(! stacks.empty())
        {
            auto cur = stacks.top();
            if ( (NULL == cur->left && NULL == cur->right) //is leaf node or
                || (last && (last == cur->left || last == cur->right)) )// children have been visited
                {
                    result.push_back(cur->val);
                    stacks.pop();
                    last = cur;
                }
            else//has children, push right then left
            { 
                if(cur->right)
                    stacks.push(cur->right); 
                if(cur->left)
                    stacks.push(cur->left);
            }
        }
        return move(result);
    }

思路五:Morris遍历

> 后序遍历稍显复杂,需要建立一个临时节点dump,令其左孩子是root。并且还需要一个子过程,就是倒序输出某两个节点之间路径上的各个节点。 步骤: 当前节点设置为临时节点dump。 1. 如果当前节点的左孩子为空,则将其右孩子作为当前节点。 2. 如果当前节点的左孩子不为空,在当前节点的左子树中找到当前节点在中序遍历下的前驱节点。 a) 如果前驱节点的右孩子为空,将它的右孩子设置为当前节点。当前节点更新为当前节点的左孩子。 b) 如果前驱节点的右孩子为当前节点,将它的右孩子重新设为空。倒序输出从当前节点的左孩子到该前驱节点这条路径上的所有节点。当前节点更新为当前节点的右孩子。 3. 重复以上1、2直到当前节点为空。

    vector<int> reverse(TreeNode * from, TreeNode * to)
    {
        vector<int> path;
        while(true)
        {
            path.push_back(from->val);
            if(from == to)
                break;
            from = from->right;
        }
        std::reverse(path.begin(), path.end());
    return move(path);
    }
    vector<int> postMorris(TreeNode * root)
    {
        TreeNode dump(-1);
        dump.left = root;
        TreeNode * cur = &dump;
        vector<int> result;
        while(cur != NULL)
        {
            if(NULL == cur->left) //1
                cur = cur->right;
            else//2
            {
                auto pre = cur->left; //pre: left child's right most
                while(pre->right != NULL && pre->right != cur)
                    pre = pre->right;
                if(pre->right == NULL)//2.a
                {
                    pre->right = cur;
                    cur = cur->left;
                }else // 2.b
                {
                    pre->right = NULL;
                    auto path = reverse(cur->left, pre);
                    std::copy(path.begin(), path.end(), back_insert(result));
                    cur = cur->right;
                }
            }
        }
        return move(result);
    }

以上都用了O(n)的时间+O(n)的空间. 还有就是传说中的利用了线索二叉树O(1)的空间的Morris遍历算法. 主要就是利用了叶子节点的孩纸指针, 指向后继节点记录回退的位置。 讲得清晰,我就不重复了。 将后续遍历的算法copy过来.

Binary Tree Postorder Traversal
这篇文章