Given a binary tree, return the inorder traversal of its nodes' values.
Example
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,3,2].
Solution
(1) all way down to the end of left
(2) curr could be left , root and right , the root and left is ajacent.
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree.
@return: Inorder in ArrayList which contains node values.
"""
def inorderTraversal(self, root):
# write your code here
if root == None:
return []
stack = []
result = []
curr = root
while curr or stack:
while curr:
stack.append(curr)
curr = curr.left
curr = stack.pop()
result.append(curr.val)
curr = curr.right
return result
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public IList<int> InorderTraversal(TreeNode root) {
List<int> result = new List<int>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode curr = root;
while(curr !=null || stack.Count > 0){
while(curr!=null){
stack.Push(curr);
curr = curr.left;
}
curr = stack.Pop();
result.Add(curr.val);
curr = curr.right;
}
return result;
}
}