给定一个二叉树的根节点 root
,返回 它的 中序 遍历 。
示例 1:
输入:root = [1,null,2,3] 输出:[1,3,2]
示例 2:
输入:root = [] 输出:[]
示例 3:
输入:root = [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) { if(root == null){ return new ArrayList<>(); } List<Integer> result = new ArrayList<>(); inTraverse(root,result); return result;} public void inTraverse(TreeNode root,List<Integer> result){ if(root == null){ return; } inTraverse(root.left,result); result.add(root.val); inTraverse(root.right,result); } } 迭代 /** * 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) { if (root == null) { return new ArrayList<>(); } Stack<TreeNode> stack = new Stack<TreeNode>(); List<Integer> result = new ArrayList<Integer>(); while (stack.size() > 0 || root != null) { if (root != null) { stack.push(root); root = root.left; } else { TreeNode temp = stack.pop(); result.add(temp.val); root = temp.right;
} } return result; } } 标签:right,TreeNode,val,中序,力扣,二叉树,left,root,result From: https://www.cnblogs.com/JavaYuYin/p/18013938