Please let me know how to make this iterative method run faster


  • 0
    D
    //  Definition for binary tree
    class TreeNode {
          int val;
          TreeNode left;
          TreeNode right;
          TreeNode(int x) { val = x; }
    }
     
    public class Solution {
        public boolean hasPathSum(TreeNode root, int sum) {
            boolean result = false; 
            int tmp = 0;
            Stack<TreeNode> stack = new Stack<TreeNode>();
            Stack<Integer> Int = new Stack<Integer>();
            TreeNode node = root;
            if (node != null) {
                stack.push(node);
                Int.push(node.val);
            }
            while (!stack.empty()) {
                tmp = tmp + node.val;
                if ((node.left == null) && (node.right == null)) {
                    if (tmp == sum) {
                        result = true;
                        return result;
                    }
                }
                if (node.right != null) {
                    stack.push(node.right);
                    Int.push(tmp);
                }
               
                if (node.left != null) {
                    node = node.left;
                }
                else {
                    node = stack.pop();
                    tmp = Int.pop();
                }
                
            }
            return result;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.