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; } }

 

Tree traversal

上一篇:layui分页失效问题


下一篇:The server selected protocol version TLS10 is not accepted by client preferences TLS12