标签:image for mic 变量 while pre lis highlight bsp

思路:中序遍历,就是按照“左,中,右”的顺序遍历一个二叉树。
1.递归,先递归左子树,之后把根节点放进res里,在递归右节点即可,可以把res设置为全局变量,或者再写一个函数,res当成参数传递都可以。代码如下,比较简单。
/**
* 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 < > ();
helper(root, res);
return res;
}
public void helper(TreeNode root, List < Integer > res) {
if (root != null) {
if (root.left != null) {
helper(root.left, res);
}
res.add(root.val);
if (root.right != null) {
helper(root.right, res);
}
}
}
}
2.不递归,可以用一个栈,如果根节点不为null,就把根节点入栈,然后指针指向左子节点(可以设置一个cur=root,移动cur,而不是直接移动root),假如根节点等于null,就出栈,把出栈的元素设置为cur,res.add(cur.val),之后,cur指向cur的右节点。
/**
* 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<>();
Stack<TreeNode> stack=new Stack<>();
TreeNode cur=root;
while(cur!=null||!stack.isEmpty())
{
if(cur!=null)
{
stack.push(cur);
cur=cur.left;
}
else
{
cur=stack.pop();
res.add(cur.val);
cur=cur.right;
}
}
return res;
}
}
标签:image for mic 变量 while pre lis highlight bsp
原文地址:https://www.cnblogs.com/lzh1043060917/p/12826463.html