Java实现二叉树的前中后序遍历(Leetcode)

 2023-09-16 阅读 28 评论 0

摘要:前序遍历: /*** 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> preorderTraversal(TreeNode root) {List<Intege

前序遍历:

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

不是二叉树可以前序遍历么、中序迭代遍历:

/*** 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> inorderTraversal(TreeNode root) {List<Integer> list=new ArrayList<Integer>();Stack<TreeNode>stack=new Stack<TreeNode>(); while(root!=null||!stack.isEmpty()) {while(root!=null) {//先将左结点入栈stack.push(root);root=root.left;}if(!stack.empty()) {root=stack.pop();list.add(root.val);root=root.right;//如果当前结点有右结点遍历它的右结点}}return list;}
}

后序迭代遍历:

/*** 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<Integer>();Stack<TreeNode>stack=new Stack<TreeNode>();TreeNode q=null;while(root!=null||!stack.isEmpty()) {while(root!=null) {stack.push(root);root=root.left;}if(!stack.empty()) {root=stack.peek();//取得结点但不让它出栈if((root.right==null)||(root.right==q)){//判断该节点的右结点是否访问过stack.pop();list.add(root.val);q=root;root=null;}else{root=root.right;}}}return list;}
}

二叉树的遍历图解例题。 

 

 

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/2/67490.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息