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?
The methods and the ideas:
inorder -> FILO (First In, Last Out) -> stack
Java Iterative(迭代,没有调用自己)
Step 1: push nodes in stack
if stack != null and root != null -> find the left node and push left node into stack
until root == null -> there’s no left root any more -> no root should be push into stack
Step 2: pop out the top node from stack
if root == null -> pop the top node from stack and add it into the result list
until stack == null-> continue to find right nodes
Step 3: do Step1 and Step 2 for right nodes.
root = root.right
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> l = new ArrayList<Integer>();
if(root == null) return l;
Stack<TreeNode> stack = new Stack<>();
while(!stack.isEmpty() || root !=null){
while(root != null){
stack.push(root);
root = root.left;
}
root = stack.pop();
l.add(root.val);
root = root.right;
}
return l;
}
}
Java Recursive solution
Recursion: a function being defined is applied within its own definition
defined what?
defined: move from current node as root to left or right node as next new root.
so I need to create a function:
traverse(current_node, result_list):
* base case : current_node = null -> return
* inorder:
* first: deal left
* second: current_node->add into result_list
* last: deal right
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List list = new ArrayList();
return getInOrder(root,list);
}
private List getInOrder(TreeNode root,List list){
if(root == null){
return list;
}
if(root.left != null){
getInOrder(root.left, list);
}
list.add(root.val);
if(root.right != null){
getInOrder(root.right,list);
}
return list;
}
}
本文详细介绍了二叉树的中序遍历算法,包括迭代和递归两种实现方式。迭代方法使用栈来辅助处理节点,而递归方法则直接通过函数自身调用来实现。文章提供了完整的Java代码示例,帮助读者理解并掌握二叉树中序遍历的实现细节。
745

被折叠的 条评论
为什么被折叠?



