本文主要是介绍leetcode:(94) Binary Tree Inorder Traversal(java),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
package HashTable;/*** 题目:* Given a binary tree, return the inorder traversal of its nodes' values.* 解题思路:* 从根节点开始,先将根节点压入栈,然后再将其所有左子结点压入栈,然后取出栈顶节点,保存节点值,* 再将当前指针移到其右子节点上,若存在右子节点,则在下次循环时又可将其所有左子结点压入栈中。* 这样就保证了访问顺序为左-根-右*/import java.util.ArrayList; import java.util.List; import java.util.Stack;public class InorderTraversal_94_1019 {public List<Integer> InorderTraversal(TreeNode root) {List<Integer> result = new ArrayList<>();Stack<TreeNode> stack = new Stack<>();TreeNode cur = root;while (cur != null || !stack.empty()) {while (cur != null) {stack.push(cur);cur = cur.left;}cur = stack.pop();result.add(cur.val);cur = cur.right;}return result;}public static void main(String[] args) {TreeNode root = new TreeNode(1);TreeNode node1 = new TreeNode(2);TreeNode node2 = new TreeNode(3);root.right = node1;node1.left = node2;InorderTraversal_94_1019 test = new InorderTraversal_94_1019();List<Integer> result = test.InorderTraversal(root);System.out.println(result);} }
这篇关于leetcode:(94) Binary Tree Inorder Traversal(java)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!