LeetCode—94. Binary Tree Inorder Traversal
题目
https://leetcode.com/problems/binary-tree-inorder-traversal/description/
中序遍历二叉树。
思路及解法
写的时候还是不熟练,还要好好想想,所以不要不重视。。
1.递归
2.非递归,栈
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
inOrder(root);
return list;
}
public void inOrder(TreeNode node){
if(node==null) return;
if(node.left!=null){
inOrder(node.left);
}
list.add(node.val);
if(node.right!=null){
inOrder(node.right);
}
}
}
/**
* 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> list = new ArrayList<>();
if (root == null) {
return list;
}
Stack<TreeNode> stack = new Stack<>();
while(root!=null || !stack.isEmpty()){
if(root!=null){
stack.push(root);
root = root.left;
}else{
root = stack.pop();
list.add(root.val);
root = root.right;
}
}
return list;
}
}