标签:without color private vat turn push nod function one
in order traversal /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<>(); if(root == null) return result; Stack<TreeNode> stack = new Stack<>(); pushLeft(root, stack); while(!stack.isEmpty()){ TreeNode cur = stack.pop(); result.add(cur.val); if(cur.right != null){ pushLeft(cur.right, stack); } } return result; } private void pushLeft(TreeNode root, Stack<TreeNode> stack){ while(root != null){ stack.push(root); root = root.left; } } } /////// recursion with global var class Solution { List<Integer> result = new ArrayList<>(); // has to be here so theres only one result , the result here is global variable public List<Integer> inorderTraversal(TreeNode root) { if(root == null) return result; if(root.left != null) inorderTraversal(root.left); result.add(root.val); if(root.right != null) inorderTraversal(root.right); return result; } } ///////. recursion without global var, with a helper function class Solution { public List < Integer > inorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<>(); if(root == null) return result; helper(root, result); return result; } private void helper(TreeNode root, List<Integer> result){ if(root.left != null) helper(root.left, result); result.add(root.val); if(root.right != null) helper(root.right, result); } } /// class Solution { public List < Integer > inorderTraversal(TreeNode root) { List < Integer > res = new ArrayList < > (); helper(root, res); return res; } public void helper(TreeNode root, List < Integer > res) { if (root != null) { if (root.left != null) { helper(root.left, res); } res.add(root.val); if (root.right != null) { helper(root.right, res); } } } }
标签:without color private vat turn push nod function one
原文地址:https://www.cnblogs.com/tobeabetterpig/p/9450624.html