博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode145 Binary Tree Postorder Traversal Java题解(递归 迭代)
阅读量:4557 次
发布时间:2019-06-08

本文共 1504 字,大约阅读时间需要 5 分钟。

题目:

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

解题:

递归的还是和前面中序和先序一样。仅仅是交换一下顺序而已

public static List
result=new ArrayList
(); public static List
postorderTraversal(TreeNode root) { if(root!=null) { postorderTraversal(root.right); postorderTraversal(root.left); result.add(root.val); } return result; }
迭代的略微复杂一些  整体上和前面的解法是一样的  只是这边要先訪问左右节点,相同还是以左节点作为主线,只是这里要添加一个栈记录每一个节点的右节点是否已经被訪问过。仅仅有当左右节点都被訪问的前提下才干訪问根节点

public static List
postorderTraversal2(TreeNode root) { List
res=new ArrayList<>(); Stack
nodeStack=new Stack<>(); Stack
nodeState=new Stack<>();//记录右节点是否已经訪问过,1表示已经訪问了,0表示未訪问 if(root==null) return res; else { nodeStack.push(root); nodeState.push(0); root=root.left; } while(!nodeStack.isEmpty()) { while(root!=null) { nodeStack.push(root); nodeState.push(0); root=root.left; }//当这个循环跳出的时候 说明nodeStak栈顶的那个节点没有左节点 if(nodeState.peek()==1)//假设这时候已经訪问过右节点了 这时候就能够訪问根节点 { res.add(nodeStack.pop().val); nodeState.pop();//把根节点相应的状态值去除 } else {//訪问右节点 root=nodeStack.peek().right; nodeState.pop();//更改状态值 由0变1 nodeState.push(1); } } return res; }

转载于:https://www.cnblogs.com/lxjshuju/p/7122092.html

你可能感兴趣的文章
Mybatis步骤
查看>>
WPF自定义控件之扩展原生控件
查看>>
《区块链100问》笔记整理——42~49问
查看>>
使用Jquery+EasyUI 进行框架项目开发案例讲解之二---用户管理源码分享
查看>>
深入理解计算机系统(1.4)---并发与并行、浅谈抽象
查看>>
函数依赖的公理化系统
查看>>
rabbitmq学习(四):利用rabbitmq实现远程rpc调用
查看>>
侯捷C++学习(二)
查看>>
EasyPlayer RTSP Android安卓播放器修复播放画面卡在第一帧bug
查看>>
web项目中全局常量的添加
查看>>
搬运工程 启动!
查看>>
局部加权回归(LWR) Matlab模板
查看>>
Connect to the DSP on C6A8168/DM8168/DM8148 using CCS
查看>>
hibernate在使用getCurrentSession时提示no session found for current thread
查看>>
【Luogu1471】方差(线段树)
查看>>
【agc028E】High Elements(动态规划,线段树,贪心)
查看>>
DEV中svg图标的使用
查看>>
Codefroces Gym101572 I.Import Spaghetti-有向图跑最小环输出路径(Floyd)
查看>>
有关位运算的操作+二进制状态压缩
查看>>
Eclipse插件 -- 阿里巴巴扫描编码规插件
查看>>