step by step.
题目:
给定一个二叉树的根节点
root
,返回 它的 中序 遍历 。示例 1:
输入:root = [1,null,2,3] 输出:[1,3,2]示例 2:
输入:root = [] 输出:[]示例 3:
输入:root = [1] 输出:[1]
思路:
中序遍历:左->根->右
代码:
1.递归:
/*** 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> list = new ArrayList<Integer>();if(root==null) return list;try{list.addAll(inorderTraversal(root.left));}catch(NullPointerException e){}list.add(root.val);try{list.addAll(inorderTraversal(root.right));}catch(NullPointerException e){}return list;}
}
2.栈:
class Solution {public List<Integer> inorderTraversal(TreeNode root) {List<Integer> list = new ArrayList<Integer>();Stack<TreeNode> s = new Stack<TreeNode>();if(root==null) return list;//s.push(root);while(!s.empty()||root!=null){if(root!=null){s.push(root);root=root.left;}else{TreeNode r = s.pop();try{list.add(r.val);}catch(NullPointerException e){}root=r.right;}}return list;}
}