思路:
二叉树的遍历可以有 前序,中序,后序,层序遍历。
- 前序:头左右
- 中序:左头右
- 后序:左右头
- 层序:从左往右依次遍历
实现方式:
- 递归
- 通过栈结构便于回溯
代码如下:
class Solution {public List<Integer> inorderTraversal(TreeNode root) {List<Integer> list = new ArrayList<>();if (root==null){return list;}process(root,list);return list;}
//递归public void process(TreeNode node,List<Integer> list){if (node==null){return;}process(node.left,list);list.add(node.val);process(node.right,list);}//非递归public List<Integer> inorderTraversal02(TreeNode root){List<Integer> list = new ArrayList<>();if (root==null){return list;}Stack<TreeNode> stack = new Stack<>();TreeNode cur=root;while (cur!=null||!stack.isEmpty()){while (cur!=null){stack.push(cur);cur=cur.left;}cur=stack.pop();list.add(cur.val);cur=cur.right;}return list;}
}