leetcode 94. Binary Tree Inorder Traversal
Given a binary tree, return the inorder traversal of its nodes' values.Example:
Input:
1
\
2
/
3
Output:
Follow up: Recursive solution is trivial, could you do it iteratively?
/**
* 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> list = new ArrayList<Integer>();
if(root == null) return list;
help(root,list);
return list;
}
public void help(TreeNode root, List<Integer> list){
if(root == null) return;
if(root.left == null && root.right == null){
list.add(root.val);
}
else if(root.left != null && root.right == null) {
help(root.left, list);
list.add(root.val);
}
else if(root.right != null && root.left == null){
list.add(root.val);
help(root.right,list);
}
else{
help(root.left,list);
list.add(root.val);
help(root.right,list);
}
}
}
/**
* 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> list = new ArrayList<Integer>();
Stack <TreeNode> stack = new Stack<>();
TreeNode c = root;
while(c != null || !stack.isEmpty()){
while(c != null){
stack.push(c);
c = c.left;
}
c = stack.pop();
list.add(c.val);
c = c.right;
}
return list;
}
}
页:
[1]