给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
2
/
3
输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
理解
中序遍历是左子树、根、右子树。这个是同一个规律适用于整个树,所以使用递归。结束条件为没有发现值,即节点为null。
/**
* 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>();
funcation(root,res);
return res;
}
public void funcation(TreeNode root,List<Integer> res){
if(root==null){
return;
}
funcation(root.left,res);
res.add(root.val);
funcation(root.right,res);
}
}
funcation(root.left,res);
寻找距离root最远的左节点,加入到res集合,否则就直接停止
if(root==null){
return;
}
res.add(root.val);
然后把根加入到res集合
res.add(root.val);
funcation(root.right,res);
寻找距离root最近右节点,加入到res集合,否则就直接停止
res.add(root.val);
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
栈:先进后出
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res=new ArrayList<Integer>();
Deque<TreeNode> stacks = new LinkedList<TreeNode>();
while(root!=null||!stacks.isEmpty()){
while(root!=null){
stacks.push(root);
root=root.left;
}
root=stacks.pop();
res.add(root.val);
root=root.right;
}
return res;
}
}