package com.app.main.LeetCode.tree;
import com.app.main.LeetCode.base.TreeNode;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* 94
*
* medium
*
* 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?
*
*
* Created with IDEA
* author:Dingsheng Huang
* Date:2019/10/30
* Time:下午4:39
*/
public class BinaryTreeInorderTraversal {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
process(root, result);
return result;
}
private void process(TreeNode root, List<Integer> result) {
if (root != null) {
if (root.left != null) {
process(root.left, result);
}
result.add(root.val);
// 这里的上下文有两种情况,一种是刚遍历完左叶子节点(跳过), 一种是刚遍历完根节点(往右子树遍历)
if (root.right != null) {
process(root.right, result);
}
}
}
public List<Integer> inorderTraversal2(TreeNode root) {
List<Integer> result = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode curr = root;
while (curr != null || !stack.isEmpty()) {
// 处理左子树
while (curr != null) {
stack.push(curr);
curr = curr.left;
}
curr = stack.pop();
result.add(curr.val);
// 这里的上下文有两种情况,一种是刚遍历完左叶子节点(跳过), 一种是刚遍历完根节点(往右子树遍历)
curr = curr.right;
}
return result;
}
}