1 Star 0 Fork 0

ZechariahZheng / blog文档

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
LeetCode_94 二叉树的中序遍历.md 900 Bytes
一键复制 编辑 原始数据 按行查看 历史

LeetCode_94 二叉树的中序遍历

思路:非递归

1、栈后法;先入栈,再访问

2、中序遍历,左臂入栈;前序遍历,栈后法+右左孩子入栈

/**
 * 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<>();
        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();
                list.add(cur.val);
                cur = cur.right;
            }
        }
        return list;
    }
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/ZechariahZheng/blog_document.git
git@gitee.com:ZechariahZheng/blog_document.git
ZechariahZheng
blog_document
blog文档
master

搜索帮助

344bd9b3 5694891 D2dac590 5694891