112. Path Sum

题目:112. Path Sum

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/
4 8
/ /
11 13 4
/ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

1,递归
 public boolean hasPathSum(TreeNode root, int sum) {
        if(root == null){
            return false;
        }
        return dfs(root,0,sum);
     }
     
     private boolean dfs(TreeNode root, int curSum, int sum){
         if(root.left == null && root.right == null){
            return (curSum + root.val) == sum;
         }
         
         if(root.left != null && root.right != null){
            return dfs(root.left,curSum + root.val,sum) || dfs(root.right,curSum + root.val,sum); 
         }
         
         if(root.left != null && root.right == null){
            return dfs(root.left,curSum + root.val,sum);
         }
         
         return dfs(root.right,curSum + root.val,sum);
     }
2,利用后序遍历
思路:后序非递归遍历,栈顶节点到栈底节点就是栈顶的节点到树根的路径
public boolean hasPathSum(TreeNode root, int sum) {
        if(root == null){
            return false;
        }
        
        //根节点到栈顶节点的路径
        Stack pathsStack = new Stack();
        TreeNode node = root;
        TreeNode tempNode = null;
        boolean hasVisited = true;
        do{
            while(node != null){
              pathsStack.push(node);
              node = node.left;
            }
            
            tempNode = null;
            hasVisited = true;
            while(!pathsStack.empty() && hasVisited){
                node = pathsStack.peek();
                if(tempNode == node.right){
                    tempNode = pathsStack.pop();
                    //判断根节点到叶子节点的路径和
                    if(tempNode.left == null && tempNode.right == null){
                        int pathSum = tempNode.val;
                        for(TreeNode treeNode : pathsStack){
                            pathSum += treeNode.val;
                        }
                    
                        if(sum == pathSum){
                            return true;
                        }
                    }
                }else{
                    node = node.right;
                    hasVisited = false;
                }
            }
            
        }while(!pathsStack.empty());
        
        return false;
    }

你可能感兴趣的:(112. Path Sum)