二叉树的中序遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
1.递归
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
inorder(root,res);
return res;
}
public void inorder(TreeNode root,List<Integer> res){
if(root ==null)
return ;
inorder(root.left,res);
res.add(root.val);
inorder(root.right,res);
}
}
2.迭代
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> st = new Stack<TreeNode>();
while(st.size()>0||root!=null){
if(root!=null){
st.add(root);
root=root.left;
}else{
TreeNode temp = st.pop();
res.add(temp.val);
root=temp.right;
}
}
return res;
}
}

浙公网安备 33010602011771号