[LeetCode] 94. Binary Tree Inorder Traversal Java
题目:
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree [1,null,2,3]
,
1 \ 2 / 3
return [1,3,2]
.
题意及分析:简单来讲就是给出一个二叉树,要求给出中序遍历的结果。最简单的方法是直接对tree进行中序遍历,如下:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> res=new ArrayList<>(); bfs(res,root); System.out.println(res); return res; } public void bfs(List<Integer> res,TreeNode node) { if(node!=null){ bfs(res,node.left); res.add(node.val); bfs(res, node.right); } } }
但是这样使用的递归,我们还可以使用非递归的代码(这里借助于stack):
public List<Integer> inorderTraversal(TreeNode root) { List<Integer> res=new ArrayList<>(); Stack<TreeNode> stack=new Stack<>(); TreeNode node=root; while(node!=null||!stack.isEmpty()){ if(node!=null){ stack.push(node); node=node.left; }else{ node=stack.pop(); res.add(node.val); node=node.right; } } return res; }