数据结构:树


1.二叉树

1.二叉树中序(根)遍历

1.递归

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
    	List<Integer> ans = new ArrayList<Integer>();
    	inorder(ans, root);
    	return ans;
    }
    
    public void inorder(List<Integer> ans,TreeNode root) {
    	if(root==null) {
    		return;
    	}
    	
    	inorder(ans, root.left);
    	ans.add(root.val);
    	inorder(ans, root.right);
    } 
}

2.迭代

    public List<Integer> inorderTraversal(TreeNode root) {
    	List<Integer> ans = new ArrayList<Integer>();
    	Deque<Integer> stack = new ArrayDeque<Integer>();
    	while(root!=null||!stack.isEmpty()) {
    		while(root!=null) {
    			stack.addLast(root);
    			root = root.left;
    		}
    		root = stack.removeLast();
    		ans.add(root.val);
    		root = root.right;
    	}
    }

3.Morris 遍历算法

注意:使用这种算法可以将时间复杂度降为O(1),每个节点会被访问两次,因此时间复杂度相当于O(2n)

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

Morris 遍历算法整体步骤如下(假设当前遍历到的节点为 xx):

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

观看动图演示,见官方题解。94. 二叉树的中序遍历

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值