标签:order value do it des empty ISE new span rsa
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]
Follow up: Recursive solution is trivial, could you do it iteratively?
M1: recursive
time: O(n), space: O(height)
/** * 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> res = new ArrayList<>(); if(root == null) { return res; } inorder(root, res); return res; } public void inorder(TreeNode node, List<Integer> res) { if(node == null) { return; } inorder(node.left, res); res.add(node.val); inorder(node.right, res); } }
M2: iterative
time: O(n), space: O(n) -- worst case
/** * 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> res = new ArrayList<>(); if(root == null) { return res; } Stack<TreeNode> s = new Stack<>(); TreeNode cur = root; while(cur != null || !s.isEmpty()) { while(cur != null) { s.push(cur); cur = cur.left; } cur = s.pop(); res.add(cur.val); cur = cur.right; } return res; } }
94. Binary Tree Inorder Traversal - Medium
标签:order value do it des empty ISE new span rsa
原文地址:https://www.cnblogs.com/fatttcat/p/10204202.html