三序遍历以及Vertical Order

本文详细介绍了二叉树的前序、中序和后序遍历算法,包括递归和迭代实现方式,并针对二叉搜索树(BST)提供了特定的优化方案。

Binary Tree Preorder Traversal

  • preorder 直接用 stack;
  • inorder 用 stack + cur;
  • postorder 用 stack + cur + prev;
  • 递归 ✓
  • 迭代 ✓
  • parent ✓
  • 复杂度 ✓

迭代的写法过于 trivial 就不细说了,记得因为 stack 先入后出的特点,push 的时候先 push 右边的就行。

Binary Tree Inorder Traversal

  • inorder 用 stack + cur;
stack 写法要记住的细节是,两个while循环里面都是(cur != null)

 public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<Integer>();
        Stack<TreeNode> stack = new Stack<TreeNode>();

        TreeNode cur = root;(1)准备一插到底(左子树)
        
	while(cur != null || !stack.isEmpty()){(2)
            
	    while(cur != null){
                stack.push(cur);
                cur = cur.left;
            }(3)
            
            TreeNode node = stack.pop();
            list.add(node.val);
            
	    cur = node.right;  (4)
        }

        return list;
    }
}

Inorder Successor in BST

因此在 BST 里面,确定起来就很简单了,从 root 往下走,如果当前结点root的val > p.val,左拐。每次往左拐的时候,存一下,记录着最近一个看到的比 p.val 大的 node 就行了。如果root.val > p.val,右拐。
public class Solution {
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        TreeNode rst = null;

        while(root != null){
            if(root.val > p.val){
                rst = root;
                root = root.left;
            } else {
                root = root.right;
            }
        }

        return rst;
    }
}

Inorder Predecessor in BST

这次往左走的时候不记,往右走的时候记,就行了。
public class Solution {
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        TreeNode rst = null;

        while(root != null){
            if(root.val > p.val){
                root = root.left;
            } else {
                rst = root;
                root = root.right;
            }
        }

        return rst;
    }
}

Binary Tree Postorder Traversal

public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
if(root == null)
return res;
Stack<TreeNode> s = new Stack(), path = new Stack();
s.push(root);
while(!s.isEmpty()){
TreeNode cur = s.peek();
if(!path.isEmpty() && path.peek() == root){             which means we hit t
res.add(root.val);
path.pop();
s.pop();
} else {
path.push(root);
if (root.right != null ) 
s.push(root.right);
if (root.left != null ) 
s.push(root.left);
}
}
return res;
}

这里每次当path.peek != root的时候,需要path.push(root)记录我们是怎么到当前这一步的。
然后还需要往s.push一个root.right和root.left以便继续遍历。
When top elements of both stacks are equal. (Which means we hit a deadend, and need to turn back)
  • Pop from both stacks.









### `void preorder(binarytree tree)` 函数实现思路 前序遍历(Preorder Traversal)是一种二叉树的遍历方式,其遍历顺序为:根节点 -> 左子树 -> 右子树。`void preorder(binarytree tree)` 函数的目的就是实现对二叉树的前序遍历。 ### 递归实现 以下是使用递归方式实现 `void preorder(binarytree tree)` 函数的示例代码: ```python class BinaryTree: def __init__(self, root_val): self.key = root_val self.leftChild = None self.rightChild = None def preorder(self): print(self.key) if self.leftChild: self.leftChild.preorder() if self.rightChild: self.rightChild.preorder() # 使用示例 if __name__ == "__main__": # 创建一个简单的二叉树 root = BinaryTree(1) root.leftChild = BinaryTree(2) root.rightChild = BinaryTree(3) root.leftChild.leftChild = BinaryTree(4) root.leftChild.rightChild = BinaryTree(5) # 调用前序遍历函数 root.preorder() ``` 上述代码定义了一个 `BinaryTree` 类,其中的 `preorder` 方法实现了前序遍历。在 `preorder` 方法中,首先打印当前节点的值,然后递归地调用 `preorder` 方法遍历左子树和右子树。 ### 非递归实现 也可以使用栈来实现非递归的前序遍历,以下是示例代码: ```python class BinaryTree: def __init__(self, val): self.val = val self.left = None self.right = None def preorder(root): if not root: return stack = [root] while stack: node = stack.pop() print(node.val) if node.right: stack.append(node.right) if node.left: stack.append(node.left) # 使用示例 if __name__ == "__main__": # 创建一个简单的二叉树 root = BinaryTree(1) root.left = BinaryTree(2) root.right = BinaryTree(3) root.left.left = BinaryTree(4) root.left.right = BinaryTree(5) # 调用前序遍历函数 preorder(root) ``` 在非递归实现中,使用一个栈来模拟递归调用的过程。首先将根节点压入栈中,然后循环取出栈顶节点进行访问,并将其右子节点和左子节点依次压入栈中。 ### 使用方法 - **创建二叉树**:首先需要创建一个二叉树的实例,可以根据实际需求构建不同结构的二叉树。 - **调用 `preorder` 函数**:将创建好的二叉树的根节点作为参数传递给 `preorder` 函数,即可完成前序遍历并输出结果。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值