题目描述:
给定一个二叉树,返回它的中序遍历。
代码:
/**
* 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();
if(root==null){
return res;
}
inOrder(root.left,res);
res.add(root.val);
inOrder(root.right,res);
return res;
}
public void inOrder(TreeNode root,List<Integer> list){
if(root==null){
return;
}
inOrder(root.left,list);
list.add(root.val);
inOrder(root.right,list);
}
}
//非递归方法
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList();
if(root==null){
return res;
}
Stack<TreeNode> stack = new Stack();
TreeNode curr = root;
while(!stack.isEmpty()||curr!=null){
while(curr!=null){ //直到指向最左的节点
stack.push(curr);
curr=curr.left;
}
//curr为null的情况下,操作stack,出栈并将节点赋给curr
curr=stack.pop();
//将元素入res结果中
res.add(curr.val);
//此时将curr指向其右孩子节点
curr=curr.right;
}
return res;
}
}