zoukankan      html  css  js  c++  java
  • 二叉树的后序遍历

    145 二叉树的后序遍历

    后序遍历,先访问左子树然后访问右子树然后访问根节点。

     C++代码

    /**
     * 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> v;
            stack<TreeNode*> s;
            TreeNode* cur = root;
            TreeNode* pre = NULL;
    //迭代写法,利用pre记录上一个访问过的结点,与当前结点比较,如果是当前结点的子节点,说明其左右结点均已访问,将当前结点出栈,更新pre记录的对象。 s.push(cur);
    while(!s.empty()&&cur!=NULL){ cur = s.top(); if((cur->right==NULL && cur->left==NULL)|| (pre!=NULL&&(pre==cur->left||pre==cur->right))){ v.push_back(cur->val); s.pop(); pre = cur; }else{ if(cur->right!=NULL){ s.push(cur->right); } if(cur->left!=NULL){ s.push(cur->left); } } } return v; } };

    java代码

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public List<Integer> postorderTraversal(TreeNode root) {
            List<Integer> list = new ArrayList<>();
            Stack<TreeNode> s = new Stack<>();
            s.push(root);
            TreeNode cur = root;
            TreeNode pre = null;
            while(!s.isEmpty()&&cur!=null){
                cur = s.peek();
                if((cur.left==null&&cur.right==null)||
                   ((pre!=null)&&(pre==cur.left||pre==cur.right))){
                    list.add(cur.val);
                    s.pop();
                    pre = cur;
                }else{
                    if(cur.right!=null){
                        s.push(cur.right);
                    }
                    if(cur.left!=null){
                        s.push(cur.left);
                    }
                }
            }
            return list;
        }
    }
  • 相关阅读:
    主机访问虚拟机ORACLE报错:ORA-12541: TNS:no listener解决办法&无法启动oracle listener服务解决办法
    C—杨辉三角
    C—水仙花数
    C—数组的转置
    C—完数
    C—判断素数
    C—斐波那契数列[生兔子问题]
    C—9*9乘法表
    eclipse常用快捷键(windows下)
    inline-block和text-indent在IE6,IE7下同时使用的兼容问题解决方法
  • 原文地址:https://www.cnblogs.com/dong973711/p/10828158.html
Copyright © 2011-2022 走看看