给定一个二叉树,返回其中序遍历。
例如:
给定二叉树 [1,null,2,3],
1
2
/
3
返回 [1,3,2].
说明: 递归算法很简单,你可以通过迭代算法完成吗?
详见:https://leetcode.com/problems/binary-tree-inorder-traversal/description/
Java实现:
递归实现:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> res=new ArrayList<Integer>(); if(root==null){ return res; } helper(root,res); return res; } private void helper(TreeNode root,List<Integer> res){ if(root==null){ return; } helper(root.left,res); res.add(root.val); helper(root.right,res); } }
非递归实现:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> res=new ArrayList<Integer>(); if(root==null){ return res; } Stack<TreeNode> stk=new Stack<TreeNode>(); while(root!=null|!stk.isEmpty()){ if(root!=null){ stk.push(root); root=root.left; }else{ root=stk.pop(); res.add(root.val); root=root.right; } } return res; } }