Binary Tree Paths

Given a binary tree, return all root-to-leaf paths.
Example
Given the following binary tree:
1
/
2 3

5

All root-to-leaf paths are:
[ "1->2->5", "1->3"]

遇到二叉樹的題一般都會用到遞歸遍歷,這題就是一個變形,要找所以的路徑,思路就是從root開始一直記錄路徑上的所有節(jié)點,然后當遍歷到leaf的時候,我們就把路徑加入到result中。
把path存在字符串中做遞歸剛開始也沒想到,后來看了別人的思路覺得代碼寫起來簡潔很多,所有就you'hua'le'xia

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root the root of the binary tree
     * @return all root-to-leaf paths
     */
    public List<String> binaryTreePaths(TreeNode root) {
        // Write your code here
        List<String> result = new ArrayList<String>();
        if (root != null) {
            findPath(result, root, String.valueOf(root.val));
        }
        
        return result;
    }
    
    public void findPath(List<String> result, TreeNode p, String path) {
        if(p == null) {
            return ;
        }
        if (p.left == null && p.right == null) {
            result.add(path);  
            return ;
        }
        
        if(p.left != null) {
            findPath(result, p.left, path + "->" + String.valueOf(p.left.val));
        }
        
        if(p.right != null) {
            findPath(result, p.right, path + "->" + String.valueOf(p.right.val));
        }
        
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容