Given a binary tree, return the inorder traversal of its nodes' values.
Example:
Input: [1,null,2,3] 1 2 / 3 Output: [1,3,2]
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: res = [] if root is None: return res stack = [] cur = root while cur or stack: while cur: stack.append(cur) cur = cur.left node = stack.pop() res.append(node.val) cur = node.right return res
/** * 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) { LinkedList<TreeNode> stack = new LinkedList<>(); List<Integer> res = new ArrayList<>(); TreeNode cur = root; while (!stack.isEmpty() || cur != null) { if (cur != null) { stack.offerFirst(cur); cur = cur.left; } else { cur = stack.pollFirst(); res.add(cur.val); cur = cur.right; } } return res; } }