编程--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].

后序遍历:根据左右根的顺序遍历的,用递归的方法就比较简单了

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> s;
    vector<int> postorderTraversal(TreeNode *root) {
        if(root==NULL)
        {
            return s;
        }
        postorderTraversal(root->left);//左子树
        postorderTraversal(root->right);//右子树
        s.push_back(root->val);//根
        return s;
    }
};

非递归的思路:

1.遍历树的左子树,并且压栈,直到左子树为空

2.左子树为空时,就记录栈顶元素,如果栈顶元素的右子树为空或者栈顶元素的右子树为上一次已经被后序遍历完树的根时,就把压入栈的元素,出栈,并且打印出来。同时记录上一次已经被后序遍历完树的根等于栈顶元素                            

3.  用同样的方法遍历右子树。     

后序遍历结果为4 6 5 2 3 1

                       

猜你喜欢

转载自blog.csdn.net/snowyuuu/article/details/81809597
今日推荐