【LeetCode每日一题】[中等]145. 二叉树的后序遍历

【LeetCode每日一题】[中等]145. 二叉树的后序遍历

145. 二叉树的后序遍历

题目来源
算法思想:树,递归,后序遍历

题目:

java代码–递归

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 * }
 */
class Solution {
    
    
    List<Integer> res = new ArrayList<Integer>();
	public List<Integer> postorderTraversal(TreeNode root) {
    
    
		dfs(root);
		return res;
    }
    //后序遍历,左右根
	private void dfs(TreeNode root) {
    
    
		if(root == null) {
    
    
			return;
		}
		dfs(root.left);//左子树
		dfs(root.right);//右子树
		res.add(root.val);//根
	}
}

java代码–迭代

//前序遍历的反转
class Solution {
    
    
	public List<Integer> postorderTraversal(TreeNode root) {
    
    
        LinkedList<Integer> result = new LinkedList<>();
        if (root == null) return result;
        //栈,先进后出
        //根,右,左顺序放入栈,出栈即为左右根(后序遍历)
        LinkedList<TreeNode> stack = new LinkedList<>();
        while(stack.size() > 0 || root != null){
    
     //栈非空         
            while (root != null){
    
    
                result.push(root.val);//入栈,
                stack.push(root);//入栈
                root = root.right;//向右递归
            }
            root = stack.pop();
            root = root.left;//向左遍历,对左子树进行循环
        }
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_39457586/article/details/108866494