本文共 1199 字,大约阅读时间需要 3 分钟。
题目地址:
Given a binary tree, return the inorder traversal of its nodes’ values.
For example:
Given binary tree[1,null,2,3]
, 1 \ 2 / 3
return [1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
既然不让用递归,那就只能用堆栈了。
public class BinaryTreeInorderTraversal { public static ListinorderTraversal(TreeNode root) { List res = new ArrayList<>(); if (root == null) return res; Stack stack = new Stack<>(); TreeNode node = root; while (node != null) { stack.push(node); node = node.left; } while (!stack.isEmpty()) { node = stack.pop(); res.add(node.val); if (node.right != null) { node = node.right; while (node != null) { stack.push(node); node = node.left; } } } return res; } public static void main(String[] args) { TreeNode root = new TreeNode(1); root.right = new TreeNode(2); root.right.left = new TreeNode(3); System.out.println(inorderTraversal(root)); return; }}
转载地址:http://gihii.baihongyu.com/