给定一个二叉树的根节点
root
,返回它的 中序 遍历。
示例 1:
输入:root = [1,null,2,3] 输出:[1,3,2]示例 2:
输入:root = [] 输出:[]示例 3:
输入:root = [1] 输出:[1]示例 4:
输入:root = [1,2] 输出:[2,1]示例 5:
输入:root = [1,null,2] 输出:[1,2]
//递归 加了个list我就有点晕乎乎了,要变通啊!
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list=new ArrayList();
inorder(root,list);
return list;
}
public List<Integer> inorder(TreeNode root,List<Integer> list){
if(root==null)return null;
inorder(root.left,list);
list.add(root.val);
inorder(root.right,list);
return list;
}
}
/**迭代
先一直取左子树存入栈直到取完,取完则pop栈顶节点x的值就是中序的第一个数
如果x节点存在右子树,则继续加入栈。如果不存在,继续pop栈顶。
一直pop到根节点,根节点如果有右子树,则开始右子树的中序。
**/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list=new ArrayList();
Stack<TreeNode> stack=new Stack<TreeNode>();
while(!stack.empty()||root!=null){
while(root!=null){
stack.push(root);
root=root.left;
}
root=stack.pop();
list.add(root.val);
root=root.right;
}
return list;
}
}
附一个 Morri题解动画版,没怎么弄懂https://leetcode-cn.com/problems/binary-tree-inorder-traversal/solution/dong-hua-yan-shi-94-er-cha-shu-de-zhong-xu-bian-li/