【劍指offer】二叉樹中和為某一值得路徑 java
阿新 • • 發佈:2019-01-01
路徑為從根節點到葉節點一條路徑,路徑經過的各節點數值之和等於某一給定數值,則列印路徑上的節點
- 因為需要列印滿足條件的路徑節點資訊和各節點之和,需要棧記錄經過的節點,和一個儲存數值之和的變數
- 用前序遍歷方法,可以首先訪問節點,然後將節點入棧,並將數值和之前入棧的節點值相加
- 如果當前之和否滿足給定值,判斷當前節點是否葉節點,是則列印路徑資訊
- 判斷節點左右孩子是否為空,遞迴呼叫
- 在呼叫完,返回時要將入棧的值出棧(此時棧中節點只到父節點),和變數也要變回呼叫之前的狀態
【牛客網java程式碼】//二叉樹定義 class Btree { int value; Btree leftBtree; Btree rightBtree; } private Stack<Integer> stack = new Stack<Integer>(); public void FindPath(Btree node , int sum,int currSum){ boolean isLeaf; if(node == null) return; currSum += node.value; stack.push(node.value); isLeaf = node.leftBtree == null && node.rightBtree == null; if(currSum == sum && isLeaf){ System.out.println("Path:"); for(int val : stack){ System.out.println(val); } } if(node.leftBtree != null) FindPath(node.leftBtree, sum, currSum); if(node.rightBtree != null) FindPath(node.rightBtree, sum, currSum); currSum -= node.value; stack.pop(); }
import java.util.ArrayList; import java.util.Stack; /** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) { ArrayList<ArrayList<Integer>> pathList= new ArrayList<ArrayList<Integer>>(); if(root==null) return pathList; Stack<Integer> stack=new Stack<Integer>(); FindPath(root,target,stack,pathList ); return pathList; } private void FindPath(TreeNode root, int target, Stack<Integer> path, ArrayList<ArrayList<Integer>> pathList) { if(root==null) return; if(root.left==null&&root.right==null){ if(root.val==target){ ArrayList<Integer> list= new ArrayList<Integer>(); for(int i:path){ list.add(new Integer(i)); } list.add(new Integer(root.val)); pathList.add(list); } } else{ path.push(new Integer(root.val)); FindPath(root.left, target-root.val, path, pathList); FindPath(root.right, target-root.val, path, pathList); path.pop(); } } }