二叉树的中序遍历:
规则:左-根-右 依次遍历即可
一 递归遍历
首先想到的便是递归调用(对于求深度的搜索遍历的这种类型,找出条件返回点,往往递归是比较好想到的)
/**
* 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> result = new ArrayList<>();
inorder(root,result);
return result;
}
public void inorder(TreeNode root,List<Integer> list){
if (root==null){
return;
}
//左
inorder(root.left,list);
//根
list.add(root.val);
//右
inorder(root.right,list);
}
}
二 利用栈来进行遍历操作
借助栈来进行遍历条件
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
Deque<TreeNode> stk = new LinkedList<TreeNode>();
while (root != null || !stk.isEmpty()) {
while (root != null) {
stk.push(root);
root = root.left;
}
root = stk.pop();
res.add(root.val);
root = root.right;
}
return res;
}
}