zoukankan      html  css  js  c++  java
  • 树遍历非递归

    非递归的遍历模板

    1.先序遍历 根左右

    Stack<TreeNode> stack = new Stack<>();
    while(!stack.isEmpty() || root != null){
    	while(root != null){
               visit(根节点)
    	   stack.push(root);
    	   root = root.left;
    	}
    	root = stack.pop();
    	root = root.right;
    }
    

    2.中序遍历 左根右

    Stack<TreeNode> stack = new Stack<>();
    while(!stack.isEmpty() || root != null){
    	while(root != null){
    	  stack.push(root);
    	  root = root.left;
    	}
    	root = stack.pop();
    	visit(根节点)
    	root = root.right;
    }
    

    3.后序遍历 左右根

    3.1 如果只是希望获得后序遍历结果

    //观察可知 后序遍历为 左右根 ,逆序是 根右左,而先序遍历是 根左右
    //所以只需要简单的改造先序遍历,使其变为根右左
    //然后将访问结果reverse即为后序遍历结果
    Stack<TreeNode> stack = new Stack<>();
    List<Integer> list = new ArrayList<>();
    while (!stack.isEmpty() || root != null) {
    	while (root != null) {
    	  list.add(root.val);
    	  stack.push(root);
    	  root = root.right;
    	}
    	root = stack.pop();
    	root = root.left;
    }
    Collections.reverse(list);
    

    3.2 若不仅仅只是想获得后序遍历结果,而是每次都需要进行一些处理

    Stack<TreeNode> stack = new Stack<>();
    List<Integer> list = new ArrayList();
    TreeNode lastVisitedNode = null;
    while (!stack.isEmpty() || root != null) {
    	while (root != null) {
    	  stack.push(root);
    	  root = root.left;
    	}
    	TreeNode topNode = stack.peek();
    	if (topNode.right != null && topNode.right != lastVisitedNode) root = topNode.right;
    	else {
    	  stack.pop();
    	  //visit(node) -- list.add(topNode.val);
    	  lastVisitedNode = topNode;
    	}
    }
    return list
    
  • 相关阅读:
    【2020-04-14】吃一折,长一智吧
    对“沟通成本”模型的一个重新假设
    【2020-04-13】稀缺才能让人珍惜
    【2020-04-12】决策都是当前认知的反映
    hhhhh我进步啦!
    求后序遍历(信息学奥赛一本通 1339)
    数的划分(信息学奥赛一本通 1304 洛谷 1025)
    memset函数怎么用嘞↓↓↓
    stack函数怎么用嘞?↓↓↓
    终于开通博客啦!
  • 原文地址:https://www.cnblogs.com/INnoVationv2/p/15221468.html
Copyright © 2011-2022 走看看