阅读 76

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 preorderTraversal(TreeNode root) {
        List result  = new ArrayList();
        if(root==null) return result;
        Stack 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 inorderTraversal(TreeNode root) {
        List result  = new ArrayList();
        if(root==null) return result;
        Stack 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 postorderTraversal(TreeNode root) {
        List result = new ArrayList();
        if(root==null) return result;
        Stack 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

文章分类
代码人生
文章标签
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐