TreeNode给定一个二叉树的根节点 root
,返回它的 中序 遍历。
两种方式:递归(先序后序也要掌握)或非递归
/**
* 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 ListinorderTraversal(TreeNode root) {
Listlist = new ArrayList<>();
inOrder(root, list);
return list;
}
public void inOrder(TreeNode root, Listlist) {
if(root == null) {
return;
}
inOrder(root.left, list);
list.add(root.val);
inOrder(root.right, list);
}
}
//非递归方式
class Solution {
public ListinorderTraversal(TreeNode root) {
Listlist = new ArrayList<>();
Stackstack = new Stack<>();
//Dequestack = new LinkedList ();
//栈非空是isEmpty()而不是!=null
while(root != null || !stack.isEmpty()) {
while(root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
list.add(root.val);
root = root.right;
}
return list;
}
}
作者:哥们要飞