代码如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for binary tree | |
* public class TreeNode { | |
* int val; | |
* TreeNode left; | |
* TreeNode right; | |
* TreeNode(int x) { val = x; } | |
* } | |
*/ | |
public class Solution { | |
public List<Integer> inorderTraversal(TreeNode root) { | |
List<Integer> res = new ArrayList<Integer>(); | |
if (root == null) | |
return res; | |
TreeNode curr = root; | |
Stack<TreeNode> path = new Stack<TreeNode>(); | |
while (!path.isEmpty() || curr != null) { | |
while (curr != null) { | |
path.push(curr); | |
curr = curr.left; | |
} | |
curr = path.pop(); | |
res.add(curr.val); | |
curr = curr.right; | |
} | |
return res; | |
} | |
} |
Follow up: constant space的中序遍历, Binary Search Tree Iterator
No comments:
Post a Comment