Morris 中序遍历

Morris 中序遍历是另一种遍历二叉树的方法,它能将非递归的中序遍历空间复杂度降为 O(1)。

  1. 如果 x 无左孩子,先将 xx 的值加入答案数组,再访问 xx 的右孩子,即 x = x.\textit{right}x=x.right。
  2. 如果 xx 有左孩子,则找到 xx 左子树上最右的节点(即左子树中序遍历的最后一个节点,xx 在中序遍历中的前驱节点),我们记为 predecessor。根据 predecessor 的右孩子是否为空,进行如下操作。
  • 如果 predecessor 的右孩子为空,则将其右孩子指向 xx,然后访问 xx 的左孩子,即 x = x.\textit{left}x=x.left。
  • 如果 predecessor 的右孩子不为空,则此时其右孩子指向 xx,说明我们已经遍历完 xx 的左子树,我们将 \textit{predecessor}predecessor 的右孩子置空,将 xx 的值加入答案数组,然后访问 xx 的右孩子,即 x = x.\textit{right}x=x.right。

重复上述操作,直至访问完整棵树。

代码:

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        TreeNode predecessor = null;

        while (root != null) {
            if (root.left != null) {
                // predecessor 节点就是当前 root 节点向左走一步,然后一直向右走至无法走为止
                predecessor = root.left;
                while (predecessor.right != null && predecessor.right != root) {
                    predecessor = predecessor.right;
                }
                
                // 让 predecessor 的右指针指向 root,继续遍历左子树
                if (predecessor.right == null) {
                    predecessor.right = root;
                    root = root.left;
                }
                // 说明左子树已经访问完了,我们需要断开链接
                else {
                    res.add(root.val);
                    predecessor.right = null;
                    root = root.right;
                }
            }
            // 如果没有左孩子,则直接访问右孩子
            else {
                res.add(root.val);
                root = root.right;
            }
        }
        return res;
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 编写非递归遍历算法 对于二叉树的遍历,常用的非递归方法有使用栈和Morris遍历。这里我们使用栈实现非递归遍历。 先序遍历: ```python def preorder(root): stack = [root] res = [] while stack: node = stack.pop() if node: res.append(node.val) stack.append(node.right) stack.append(node.left) return res ``` 中序遍历: ```python def inorder(root): stack = [] node = root res = [] while stack or node: while node: stack.append(node) node = node.left node = stack.pop() res.append(node.val) node = node.right return res ``` 后序遍历: ```python def postorder(root): stack = [(root, False)] res = [] while stack: node, visited = stack.pop() if node: if visited: res.append(node.val) else: stack.append((node, True)) stack.append((node.right, False)) stack.append((node.left, False)) return res ``` 2. 实现给定一棵二叉树的先序遍历序列和中序遍历序列,创建这棵树。 我们可以使用递归的方式进行构建。先序遍历的第一个节点必定是根节点,然后在中序遍历中找到这个节点,左边的是左子树,右边的是右子树。 代码实现如下: ```python def buildTree(preorder, inorder): if not preorder or not inorder: return None root_val = preorder[0] root = TreeNode(root_val) idx = inorder.index(root_val) root.left = buildTree(preorder[1:idx+1], inorder[:idx]) root.right = buildTree(preorder[idx+1:], inorder[idx+1:]) return root ``` 3. 输出二叉树的后序遍历结点序列 后序遍历的顺序是左右根,可以使用递归的方式实现: ```python def postorderTraversal(root): if not root: return [] return postorderTraversal(root.left) + postorderTraversal(root.right) + [root.val] ``` 也可以使用非递归的方式实现,类似于非递归的先序遍历: ```python def postorderTraversal(root): if not root: return [] stack = [(root, False)] res = [] while stack: node, visited = stack.pop() if node: if visited: res.append(node.val) else: stack.append((node, True)) stack.append((node.right, False)) stack.append((node.left, False)) return res ``` 4. 输出二叉树的叶子结点 叶子结点是指没有左右子树的节点,在遍历的过程中,遇到叶子结点就把它加到结果中即可。可以使用递归的方式实现。 ```python def getLeaves(root): if not root: return [] if not root.left and not root.right: return [root.val] return getLeaves(root.left) + getLeaves(root.right) ``` 也可以使用非递归的方式实现,使用栈来记录遍历的节点: ```python def getLeaves(root): if not root: return [] stack = [root] res = [] while stack: node = stack.pop() if node: if not node.left and not node.right: res.append(node.val) else: stack.append(node.right) stack.append(node.left) return res ``` 5. 统计二叉树的结点个数 二叉树的结点个数包括根节点、左子树的结点个数和右子树的结点个数。可以使用递归的方式实现。 ```python def countNodes(root): if not root: return 0 return countNodes(root.left) + countNodes(root.right) + 1 ``` 也可以使用非递归的方式实现,使用栈来记录遍历的节点: ```python def countNodes(root): if not root: return 0 stack = [root] count = 0 while stack: node = stack.pop() if node: count += 1 stack.append(node.left) stack.append(node.right) return count ``` 6. 求二叉树的深度 二叉树的深度等于左右子树深度的最大值加1。可以使用递归的方式实现。 ```python def maxDepth(root): if not root: return 0 return max(maxDepth(root.left), maxDepth(root.right)) + 1 ``` 也可以使用非递归的方式实现,使用队列来记录遍历的节点,并记录每个节点的深度: ```python def maxDepth(root): if not root: return 0 queue = [(root, 1)] depth = 0 while queue: node, cur_depth = queue.pop(0) if node: depth = max(depth, cur_depth) queue.append((node.left, cur_depth+1)) queue.append((node.right, cur_depth+1)) return depth ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值