Tree traversal

时间:2021-09-16
本文章向大家介绍Tree traversal,主要包括Tree traversal使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
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> preorderTraversal(TreeNode root) {
        List<Integer> result  = new ArrayList();
        if(root==null) return result;
        Stack<TreeNode> stack = new Stack();
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode temp  = stack.pop();
            result.add(temp.val);
            if(temp.right!=null) stack.push(temp.right);
            if(temp.left!=null) stack.push(temp.left);
        }
        return result;
    }
}

二叉树中序遍历(非递归)

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result  = new ArrayList();
        if(root==null) return result;
        Stack<TreeNode> stack = new Stack();
        while(root!=null || !stack.isEmpty()){
            //一直向左走到头,先处理左侧节点
            while(root!=null){
                stack.push(root);
                root=root.left;
            }
            //输出当前栈顶元素
            root = stack.pop();
            result.add(root.val);
            //当前节点压入后,开始处理右侧节点  --这步总出错
            root=root.right; 
        }
        return result;        
    }
}

二叉树后序遍历(非递归)

 实际上后序遍历,只需要在先序遍历基础上稍作修改即可。

先序遍历:root -> 左 -> 右   先右后左的后序遍历: 右 -> 左 -> root

class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList();
        if(root==null) return result;
        Stack<TreeNode> stack  = new Stack();
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode temp = stack.pop();
            result.add(0,temp.val);
            if(temp.left!=null) stack.push(temp.left);
            if(temp.right!=null) stack.push(temp.right);
        }
        return result;
    }
}

原文地址:https://www.cnblogs.com/cynrjy/p/15291535.html