zoukankan      html  css  js  c++  java
  • 非递归遍历二叉树-前序中序

    思路:

    前序遍历路径上节点的值先放入list,然后把节点的right-child放入栈,一次前序遍历到叶节点的时候,去栈中取出节点,循环进行前序遍历到叶节点。最后返回list

    public class Solution {
        public ArrayList<Integer> preorderTraversal(TreeNode root) {
            ArrayList<Integer> result = new ArrayList<Integer>();
            
            Stack<TreeNode> stack = new Stack<TreeNode>();
            
            if(root == null) {
                return result;
            }
            TreeNode node = null;
            stack.add(root);
            while(!stack.empty()) {
                node  = stack.pop();
                while(node != null) {
                    result.add(node.val);
                    if(node.right != null) {
                        stack.push(node.right);
                    }
                    node = node.left;
                }
            }
            return result;
        }
    }

     非递归中序遍历如下

    public ArrayList<Integer> inorderTraversal(TreeNode root) {
            ArrayList<Integer> result = new ArrayList<Integer>();
            Stack<TreeNode> stack = new Stack<TreeNode>();
            if(root == null) {
                return result;
            }
            
            stack.add(root);
            TreeNode node = root.left;
            while(!stack.empty() || node != null) {  //第二个条件意义{1,#,2}
                while(node != null) {
                    stack.add(node);
                    node = node.left;  //左子树遍历到头,依次入栈
                }
                
                node = stack.pop();
                result.add(node.val);
                node = node.right;     //右子树遍历
            }
            return result;
        }
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }
  • 相关阅读:
    03-Tomcat服务器
    02-Http请求与响应全解
    01-Web客户端与服务器详解
    JavaScript高级程序设计31.pdf
    JavaScript高级程序设计30.pdf
    JavaScript高级程序设计29.pdf
    JavaScript高级程序设计28.pdf
    JavaScript高级程序设计27.pdf
    JavaScript高级程序设计26.pdf
    JavaScript高级程序设计25.pdf
  • 原文地址:https://www.cnblogs.com/yanghuahui/p/3489741.html
Copyright © 2011-2022 走看看