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

     思路:

    先序遍历:根-左,右

    中序遍历:左,根,右

    后序遍历:左-右-根

    可以发现,只是访问根节点顺序不同而已‘

    后序遍历,左右根,也就是根右左然后逆序!!!(先序遍历是根左右,则后续遍历时候入栈时先入左边再右边)最后的结果逆序输出一下就行!

    /**
     * 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>res=new ArrayList<Integer>();
            if(root==null)return res;
            Stack<TreeNode> stack=new Stack<TreeNode>();
            stack.push(root);
            while(!stack.isEmpty())
            {
                TreeNode n=stack.pop();
                res.add(n.val);
                if(n.left!=null)
                {
                    stack.push(n.left);
                }
                if(n.right!=null)
                {
                    stack.push(n.right);
                }
    
            }
            Collections.reverse(res);
            return res;
        }
    }
    

      

  • 相关阅读:
    mybatis LIKE模糊查询若干写法
    OKR和KPI区别和适用对象
    谈谈 Puppeteer
    jq
    tput
    nodejs + ffmpeg 实现视频转动图
    Golang IO操作
    golang 三个点的用法
    Golang Package 与 Module 简介
    Python合并字典组成的列表
  • 原文地址:https://www.cnblogs.com/lzh1043060917/p/12826670.html
Copyright © 2011-2022 走看看