简书来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal
给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]
递归解法:
/**
* 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> ans = new ArrayList<>();
inorder(ans,root);
return ans;
}
private void inorder(List<Integer> ans,TreeNode root){
if (root == null)
return;
inorder(ans,root.left);
ans.add(root.val);
inorder(ans,root.right);
}
}
迭代解法:
/**
* 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> ans = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
addLeft(stack,root);
while(!stack.empty()){
TreeNode pop = stack.pop();
ans.add(pop.val);
if (pop.right != null){
addLeft(stack,pop.right);
}
}
return ans;
}
private void addLeft(Stack<TreeNode> stack,TreeNode root){
while(root != null){
stack.push(root);
root = root.left;
}
}
}
网友评论